group_by method

The group_by method groups all elements of the collection by the return value of the given block, and returns a hash where the keys are the block return values.

Animals

# group by first letter:
['cat', 'dog', 'cow', 'horse', 'donkey'].group_by{|animal| animal[0]}
    #=> {"c"=>["cat", "cow"], "d"=>["dog", "donkey"], "h"=>["horse"]}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>