Rails:如何对OrderedHash进行排序/重新排序

时间:2010-11-30 19:15:16

标签: ruby-on-rails sorting hash

我有一个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?

1 个答案:

答案 0 :(得分:8)

好吧,我认为你可以在原始答案的:order => 'sum_deal_price ASC'电话中使用sum

但你也可以在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]