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

Kev*_*ker 6 sorting hash ruby-on-rails

我有一个OrderedHash,从这里的答案生成,看起来像这样:

<OrderedHash {2=>"534.45",7=>"10",153=>"85.0"}>
Run Code Online (Sandbox Code Playgroud)

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

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

如何重新排序此OrderedHash?

Sté*_*hen 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]
Run Code Online (Sandbox Code Playgroud)