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: , , , , .

Leave a Comment

hidden

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


Categories

posts[:recent]

episodes[:recycled]

@@name = PRAYAS

Step down at my blog with your ideas,comments,suggestions on Ruby,RoR,Ajax or Web2.0.You may reach me at
infostall@gmail.com

find_by_tags

Links

visitors[:since_Mar'08]

free web counter

Spam Blocked

Feeds

Meta

RSS Prayas here