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 *