Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 reorder this OrderedHash?

like image 896
Kevin Whitaker Avatar asked Nov 30 '10 19:11

Kevin Whitaker


People also ask

How do you sort an array of hashes in Ruby?

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)

How do you sort a hash in Ruby?

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.


1 Answers

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]
like image 67
Stéphan Kochen Avatar answered Oct 29 '22 00:10

Stéphan Kochen