Related link: http://www.ruby-doc.org/core/classes/Enumerable.html

I love when I come across something that’s SO much easier to do in one language than another.

Here’s something that I wrote a whole program to do in PHP once, that I realized is built right into Ruby:

Say you’ve got an array of any complex things (objects or hashes most likely), and you want to sort the array by one of the attributes of the things.

Ruby has this wonderful method sort_by that works on any Enumerable lists. See the man page, here.


# make an Array of kids
kids = Array.new
# each kid is a Hash
kids << {'name'=>'Cliff', 'age'=>10}
kids << {'name'=>'Bill', 'age'=>6}
kids << {'name'=>'Andy', 'age'=>13}
#
# the kids sorted by name
kids.sort_by { |k| k['name'] }
# the kids sorted by age
kids.sort_by { |k| k['age'] }