Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort not simple hash (hash of hashes)

Tags:

sorting

ruby

hash

I have a Hash like this

{ 55 => {:value=>61, :rating=>-147},
  89 => {:value=>72, :rating=>-175},
  78 => {:value=>64, :rating=>-155},
  84 => {:value=>90, :rating=>-220},
  95 => {:value=>39, :rating=>-92},
  46 => {:value=>97, :rating=>-237},
  52 => {:value=>73, :rating=>-177},
  64 => {:value=>69, :rating=>-167},
  86 => {:value=>68, :rating=>-165},
  53 => {:value=>20, :rating=>-45}
}

How can i sort it by :rating? Or maybe i should use some different structure?

like image 429
Kavu Avatar asked Dec 12 '08 07:12

Kavu


People also ask

How to 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)


1 Answers

I would change the data structure to an array of hashes:

my_array =
[
  {:id => 78, :value=>64, :rating=>-155},
  {:id => 84, :value=>90, :rating=>-220},
  {:id => 95, :value=>39, :rating=>-92}
]

You can sort this kind of structure easily with

my_array.sort_by { |record| record[:rating] }

To get the hash-like functionality of fetching a record by id you can define a new method on my_array:

def my_array.find_by_id(id) 
  self.find { |hash| hash[:id] == id }
end

so after that you can do

my_array.find_by_id(id)

instead of

my_hash[id]
like image 55
Milan Novota Avatar answered Oct 19 '22 07:10

Milan Novota