Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Ruby Index

🔄 Enumerable — Functional iteration — Ruby's most powerful mixin

Enumerable provides 60+ iteration methods mixed into Array, Hash, Range, and any class that defines each. It's the core of Ruby's expressive data processing.

📋 Methods & Functions

NameSignatureDescription
eachobj.each {|e| block} → objBasic iteration
map/collectobj.map {|e| expr} → ArrayTransform to new array
select/filterobj.select {|e| bool} → ArrayKeep matching elements
rejectobj.reject {|e| bool} → ArrayRemove matching elements
find/detectobj.find {|e| bool} → objReturn first match
reduce/injectobj.reduce(init, :sym) → valFold to single value
each_with_objectobj.each_with_object(memo) {|e,m|}Accumulate with memo
flat_mapobj.flat_map {|e| Array} → ArrayMap then flatten one level
group_byobj.group_by {|e| key} → HashGroup into hash by key
sort_byobj.sort_by {|e| key} → ArraySort by computed key
min_by/max_byobj.min_by {|e| key} → elementFind min/max by computed key
minmaxobj.minmax → [min, max]Return [minimum, maximum]
countobj.count {|e| bool} → IntegerCount matching elements
tallyobj.tally → HashCount each unique element
sumobj.sum {|e| expr} → NumberSum block results
any?obj.any? {|e| bool} → boolTrue if any element matches
all?obj.all? {|e| bool} → boolTrue if all elements match
none?obj.none? {|e| bool} → boolTrue if no elements match
one?obj.one? {|e| bool} → boolTrue if exactly one element matches
include?obj.include?(val) → boolTrue if collection contains val
each_sliceobj.each_slice(n) {|chunk| block}Iterate in chunks of n
each_consobj.each_cons(n) {|window| block}Sliding window of n
zipobj.zip(*others) → ArrayInterleave with other enumerables
chunk_whileobj.chunk_while {|a,b| bool}Group while condition holds
takeobj.take(n) → ArrayFirst n elements
take_whileobj.take_while {|e| bool} → ArrayTake while condition holds
dropobj.drop(n) → ArraySkip first n elements
lazyobj.lazy → Enumerator::LazyCreate lazy enumerator
filter_mapobj.filter_map {|e| expr_or_nil}Map and filter nils (Ruby 2.7+)
flat_mapobj.flat_map {|e| [a,b]} → ArrayMap and flatten results
each_with_indexobj.each_with_index {|e,i|}Iterate with integer index
to_a/entriesobj.to_a → ArrayConvert to array

💡 Example Program

Run with ruby script.rb.

# Enumerable — Ruby's most powerful mixin
words = %w[apple banana cherry date elderberry fig grape]

# filter_map (Ruby 2.7+)
long_upper = words.filter_map { |w| w.upcase if w.length > 4 }
puts long_upper.inspect

# each_slice: batches of 3
words.each_slice(3) { |batch| puts batch.inspect }

# each_cons: sliding window
puts "Consecutive pairs:"
[1,2,3,4,5].each_cons(2) { |a,b| print "#{a}+#{b}=#{a+b}  " }
puts

# Lazy enumerator — infinite range
result = (1..Float::INFINITY).lazy
  .map    { |n| n * n }
  .select { |n| n > 20 }
  .first(5)
puts "First 5 squares > 20: #{result.inspect}"

# chunk_while: group consecutive numbers
nums = [1, 2, 3, 10, 11, 12, 20, 21]
puts nums.chunk_while { |a,b| b - a == 1 }.map(&:inspect).inspect

# Zip + process
names  = %w[Alice Bob Carol Dave]
scores = [95, 87, 92, 78]
grade  = ->(s) { s >= 90 ? "A" : s >= 80 ? "B" : "C" }
names.zip(scores).map { |n,s| [n, s, grade.(s)] }
                 .sort_by { |_,s,_g| -s }
                 .each    { |n,s,g| printf "%-8s %d  %s\n", n, s, g }

# group_by + transform
puts words.group_by { |w| w.length }
          .sort_by  { |len,_| len }
          .map      { |len,ws| "#{len}: #{ws.join(",")}" }
          .inspect
# ruby enum_demo.rb

← File & IO  |  🏠 Index