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 reorder this OrderedHash?
You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)
To sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With