Skip to content
Enumerable
step 1/5

Reading — step 1 of 5

Learn

~1 min readCollections

Anything that includes the Enumerable module — Array, Hash, Range, Set, custom classes — gets a long list of useful methods for free.

nums = [1, 2, 3, 4, 5]

nums.map { |n| n * n }       # [1, 4, 9, 16, 25]
nums.select { |n| n > 2 }    # [3, 4, 5]
nums.reduce(:+)               # 15
nums.min                       # 1
nums.max                       # 5
nums.sort                      # [1,2,3,4,5]
nums.zip(["a","b","c"])      # [[1,"a"], [2,"b"], [3,"c"], [4,nil], [5,nil]]

Group-by, partition, and chunk are surprisingly powerful:

words = ["apple", "ant", "banana", "bee"]
words.group_by { |w| w[0] }   # { "a" => ["apple","ant"], "b" => ["banana","bee"] }

When you build a custom class, including Enumerable + defining each gives you all of these methods automatically.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…