Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort in ruby a JSON array of hashes

Tags:

ruby

So I have an array of hashes:

[{"id":"30","name":"Dave"},
 {"id":"57","name":"Mike"},
 {"id":"9","name":"Kevin"},
 ...
 {"id":"1","name":"Steve"}]

And I want to sort it by the id attribute, so that it looks like this:

[{"id":"1","name":"Steve"},
 {"id":"2","name":"Walter"},
 ...
 {"id":"60","name":"Chester"}]

I'm assuming I use the sort_by method but I'm not exactly sure how to do it.

like image 466
Cristiano Avatar asked Oct 28 '13 13:10

Cristiano


People also ask

How do you sort hashes in Ruby?

Sorting Hashes 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.

How do you sort an array of 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.

How do you sort an array of strings in Ruby?

In Ruby, it is easy to sort an array with the sort() function. When called on an array, the sort() function returns a new array that is the sorted version of the original one.


1 Answers

This should work:

array.sort_by { |hash| hash['id'].to_i }

In this case, sort_by is preferred over sort because it is more efficient. While sort calls to_i on every comparison, sort_by does it once for each element in array and remembers the result.

like image 72
Marek Lipka Avatar answered Sep 27 '22 20:09

Marek Lipka