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.
- View the objects used in these examples
- View these examples as a runnable ruby script on GitHub.
- Practice this method as an interactive kata on Codewars!
Animals
# group by first letter: ['cat', 'dog', 'cow', 'horse', 'donkey'].group_by{|animal| animal[0]} #=> {"c"=>["cat", "cow"], "d"=>["dog", "donkey"], "h"=>["horse"]}