Sorting an Array of hashes
May 13, 2008
We get a situation where we fetch some set of records from db as an array of hashes, and later we need to sort this array based on some field of DB.
Here is a very hand code to do so.
array_objs =[ {:title => "row1_title" ,:name => "Mumbai"},
{:title => "row2_title" ,:name => "Delhi"},
{:title => "row3_title" ,:name => "Bangalore"} ]
array_objs .sort_by {|array_objs| array_objs [:name] }.each do |res|
puts "#{res[:name] }"
end
O/P:
Bangalore
Delhi
Mumbai
Entry Filed under: RoR, Ruby, coding. Tags: RoR, Ruby, sort, hash, array.
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed