Mastering Enumerable, Part 1

Flashcard 3 of 7

What is the real name of mystery_method? (It's found in Enumerable.)

names = %w(ben thom joe mark)

names.mystery_method { |name| name.length }
#=> { 3 => ["ben", "joe"], 4 => ["thom", "mark"] }

That's group_by.

From the docs: "groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block and the values are arrays of elements in the collection that correspond to the key."

It's not something we reach for often, but very handy when we do.

One example: say you want to see all the orders from the past month grouped by which day they occurred.

orders.group_by { |order| order.created_at.day }

#=> { 1 => [...], 2 => [...], ... }
Return to Flashcard Results