开发者

Rails: How to sort/re-order an OrderedHash

I have an OrderedHash, generated from the answer here that looks like this:

<OrderedHash {2=>"534.45",7=>"10",153=>"85.0"}>

So, I need to sort the hash by the second value, in descending order. I tried this:

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

How can I reo开发者_运维技巧rder this OrderedHash?


Well, I think you can simply use :order => 'sum_deal_price ASC' in the sum call of the original answer.

But you can also do it in Ruby, it's just a bit trickier:

# 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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜