Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby sort_by method

Tags:

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.

like image 589
U-L Avatar asked Jan 01 '13 20:01

U-L


People also ask

How does sort_by work in Ruby?

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.

How do you sort an array in ascending order 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 objects in Ruby?

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.

Can you sort elements in a Ruby hash object?

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.


1 Answers

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 
like image 168
steenslag Avatar answered Oct 21 '22 08:10

steenslag