Enumerables and collection manipulation

Sarah Mitchell Feb 2026
3 tabs
# Map - transform elements
[1, 2, 3, 4].map { |n| n * 2 }          # => [2, 4, 6, 8]
['alice', 'bob'].map(&:upcase)          # => ['ALICE', 'BOB']
users.map(&:email)                       # => ['alice@example.com', ...]

# Select/Reject - filter elements
[1, 2, 3, 4, 5].select(&:even?)         # => [2, 4]
[1, 2, 3, 4, 5].reject(&:even?)         # => [1, 3, 5]
users.select { |u| u.active? }

# Reduce - aggregate values
[1, 2, 3, 4].reduce(:+)                 # => 10
[1, 2, 3, 4].reduce(0) { |sum, n| sum + n }  # => 10
items.reduce(0) { |total, item| total + item.price }

# Find - return first match
[1, 2, 3, 4].find(&:even?)              # => 2
users.find { |u| u.email == 'alice@example.com' }

# Group by - partition into hash
users.group_by(&:role)
# => { 'admin' => [<User>, ...], 'user' => [...] }

words = ['apple', 'apricot', 'banana', 'blueberry']
words.group_by { |word| word[0] }
# => { 'a' => ['apple', 'apricot'], 'b' => ['banana', 'blueberry'] }

# Partition - split into two arrays
numbers = [1, 2, 3, 4, 5, 6]
even, odd = numbers.partition(&:even?)
# even => [2, 4, 6], odd => [1, 3, 5]

# Any/All/None - test conditions
[1, 2, 3].any?(&:even?)                 # => true
[2, 4, 6].all?(&:even?)                 # => true
[1, 3, 5].none?(&:even?)                # => true

# Count - count matching elements
[1, 2, 3, 4].count(&:even?)             # => 2

# Tally - count occurrences (Ruby 2.7+)
['a', 'b', 'a', 'c', 'b', 'a'].tally
# => { 'a' => 3, 'b' => 2, 'c' => 1 }
3 files · ruby Explain with highlit

Ruby's Enumerable module provides rich collection methods. map transforms elements; select/reject filter. reduce aggregates values. find returns first match; find_all returns all matches. group_by partitions by criteria. partition splits into two arrays. any?, all?, none? test conditions. sort_by orders by criteria. uniq removes duplicates. flatten flattens nested arrays. zip combines arrays. Chaining methods creates expressive pipelines. Lazy enumerables defer computation until needed. Symbol-to-proc (&:method_name) shorthand improves readability. Understanding enumerables enables functional programming style—no explicit loops, declarative data transformation. Mastery of Enumerable is essential for idiomatic Ruby.