问题
I have a hash like this:
data = {"Blood Group"=>"A", "Next Review Date"=>"22/06/2016", "Tourniquet Time"=>"23", "BMI"=>"21"}
I have a sorting order in an array:
sorting_order = [1, 0, 2, 3]
I want to rearrange the hash according to the sorting order array so that the hash becomes:
data = {"Next Review Date"=>"22/06/2016", "Blood Group"=>"A", "Tourniquet Time"=>"23", "BMI"=>"21"}
I tried:
sorted_hash = sorting_order.map{|x| data[x]}
It returns:
NoMethodError: undefined method `[]' for #<Enumerator: [1, 0, 2, 3]:index>
I'm not sure of how to proceed here. What's the way to do it?
回答1:
data.to_a.values_at(*sorting_order).to_h
#=> {"Next Review Date"=>"22/06/2016", "Blood Group"=>"A",
# "Tourniquet Time"=>"23", "BMI"=>"21"}
回答2:
This should do the trick:
sorting_order.map{|x| data.to_a[x]}.to_h # We're converting hash to array in each loop, you could define a local var and use it here instead.
=> {"Next Review Date"=>"22/06/2016", "Blood Group"=>"A", "Tourniquet Time"=>"23", "BMI"=>"21"}
PS. I was one of the upvoters of @DaveNewton's comment and agree that hashes should not be sorted.
回答3:
Instead of sorting the hash every time, is it possible for you to store the hash keys in the array which holds the sort order?
like this:
data = {"Blood Group"=>"A", "Next Review Date"=>"22/06/2016", "Tourniquet Time"=>"23", "BMI"=>"21"}
sorting_order = ["Next Review Date", "Blood Group", "Tourniquet Time", "BMI"]
And when the user changes the order, you simply update the keys in the sorting_order
array.
Afterwards, when rendering the data, you simply call
sorting_order.each { |data_key| render(data[data_key]) }
来源:https://stackoverflow.com/questions/37998809/sorting-a-hash-based-on-an-array-representing-order