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.
source share