I have just started to learn ruby. I have an array of hashes. I want to be able to sort the array based on an elementin the hash. I think I should be able to use the sort_by method. Can somebody please help?
#array of hashes array = [] hash1 = {:name => "john", :age => 23} hash2 = {:name => "tom", :age => 45} hash3 = {:name => "adam", :age => 3} array.push(hash1, hash2, hash3) puts(array)
Here is my sort_by code:
# sort by name array.sort_by do |item| item[:name] end puts(array)
Nothing happens to the array. There is no error either.
sort_by works by creating what you can think of as an invisible hash. When called on an array, it calculates a set of numerical keys (known as “sort keys”), and assigns each element in the array to one of those sort keys. Then, the keys are sorted, and mapped back onto the original values.
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)
The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.
Sorting Hashes in RubyTo 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.
You have to store the result:
res = array.sort_by do |item| item[:name] end puts res
Or modify the array itself:
array.sort_by! do |item| #note the exclamation mark item[:name] end puts array
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