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?
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)
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]
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