Sort in ruby ​​array of JSON hashes

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 id attribute so that it looks like this:

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

I assume I am using the sort_by method, but I'm not quite sure how to do this.

+6
source share
3 answers

This should work:

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

In this case, sort_by preferable to sort , because it is more efficient. While sort calls to_i with each comparison, sort_by does this once for each element in the array and remembers the result.

+15
source

When I see the input, it is almost always a JSON string. Ruby does not automatically understand JSON and does not know how to convert it, but Ruby makes it easy for us to convert from / to it:

 require 'json' json_data = '[{"id":"30","name":"Dave"}, {"id":"57","name":"Mike"}, {"id":"9","name":"Kevin"}, {"id":"1","name":"Steve"}]' ary = JSON[json_data].sort_by{ |e| e['id'].to_i } ary # => [{"id"=>"1", "name"=>"Steve"}, {"id"=>"9", "name"=>"Kevin"}, {"id"=>"30", "name"=>"Dave"}, {"id"=>"57", "name"=>"Mike"}] 

The only real trick here is:

 JSON[json_data] 

You will see a lot of time that people use JSON.parse(json_data) , but the [] method is smart enough to find out if it gets a string or array or hash. If it is a string, she tries to parse it, assuming her incoming data. If it is an array or a hash, it will convert it to a JSON string for output. As a result, JSON[...] simplifies the use of the class and does this, so we do not need to use parse or to_json .

Otherwise, using sort_by preferable to using sort if you are not directly comparing two simple variables, such as integer to integer, string to string, or character to character. Once you have to dive into an object or do some calculation to determine how things are compared, you should use sort_by . See the Wikipedia article on Schwarzian’s transformation to see what’s going on under the covers. This is a very powerful method that can significantly speed up sorting.

+5
source

Your hash syntax is incorrect if they are where the characters look like this:

 data = [ {id:"30", name:"Dave"}, {id:"57", name:"Mike"}, {id:"9", name:"Kevin"}, {id:"1", name:"Steve"} ] sorted_data = data.sort_by{|x| x[:id].to_i} 

Edit: Forgot to_i, fixed. If the keys are strings: the way to determine the hash does not work, so we need hash rockets:

 data = [{"id"=>"30","name"=>"Dave"}, {"id"=>"57","name"=>"Mike"}, {"id"=>"9","name"=>"Kevin"}, {"id"=>"1","name"=>"Steve"}] sorted_data = data.sort_by{|x| x['id'].to_i} 
+2
source

Source: https://habr.com/ru/post/956878/


All Articles