Sorting a hash based on an array representing order

空扰寡人 提交于 2020-01-05 15:46:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!