ruby-on-rails – Rails:如何对OrderedHash进行排序/重新排序

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails:如何对OrderedHash进行排序/重新排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个OrderedHash,从答案 here生成,看起来像这样:
<OrderedHash {2=>"534.45",7=>"10",153=>"85.0"}>

所以,我需要按降序对第二个值进行哈希排序.我试过这个:

var.sort! {|a,b| b[1] <=> a[1]}
NoMethodError: undefined method `sort!' for #<ActiveSupport::OrderedHash:0x127a50848>

如何重新排序此OrderedHash?

解决方法

好吧,我认为你可以简单地使用:order => ‘sum_deal_price ASC’在原始答案的总和调用中.

但你也可以在Ruby中做到这一点,这有点棘手:

# You can't sort a Hash directly,so turn it into an Array.
arr = var.to_a  # => [[2,"534.45"],[7,"10"],[153,"85.0"]]
# Looks like there's a bunch of floats-as-strings in there,fix that.
arr.map! { |pair| [pair.first,pair.second.to_f] }
# Now sort it by the value (which is the second entry of the pair).
arr.sort! { |a,b| a.second <=> b.second }
# Turn it back into an OrderedHash.
sorted_hash = ActiveSupport::OrderedHash[arr]

猜你在找的Ruby相关文章