Ruby's Ruby Enumerable module is the powerhouse behind expressive, functional-style iteration. Mixed into Array, Hash, Range, Set, and custom collections, it enables clean, efficient data processing. Enhance your Ruby projects with expert Rails consulting services, optimizing each, map, and select for cleaner, high-performance code.
Ruby Enumerable: The Foundation
To use Ruby Enumerable, a class must define ciascuno:
ruby class ShoppingList include Enumerable def initialize(*items) @items = items end def each(&block) @items.each(&block) end end
Now ShoppingList supports all Ruby Enumerable methods.
Ruby Enumerable: ciascuno – Execute Per Item
What ciascuno Does
Runs a block for every element. Returns the original collection.
ruby
[1, 2, 3].each { |n| puts n * 2 }
# Output:
# 2
# 4
# 6
# Returns: [1, 2, 3]
When to Use Ruby Enumerable ciascuno
- Logging or printing
- Triggering side effects (email, API calls)
- Accumulating external state
ruby
total = 0
[10, 20, 30].each { |n| total += n }
puts total # => 60
Pitfall: Never use ciascuno expecting a transformed array.
ruby
# Wrong
[1, 2, 3].each { |n| n * 2 } # => [1, 2, 3]
Ruby Enumerable: mappa (or collect) – Transform Every Item
What mappa Does
Applies a block and returns a new array of results.
ruby
[1, 2, 3].map { |n| n * 2 } # => [2, 4, 6]
When to Use Ruby Enumerable mappa
- Converting data types
- Extracting fields
- Building new structures
Ruby Enumerable mappa Esempi
Capitalize Names
ruby ["alice", "bob"].map(&:upcase) # => ["ALICE", "BOB"]
Extract User Emails
ruby
users = [{email: "[email protected]"}, {email: "[email protected]"}]
users.map { |u| u[:email] } # => ["[email protected]", "[email protected]"]
With Index
ruby
fruits = ["apple", "banana"]
fruits.map.with_index { |f, i| "#{i + 1}. #{f}" }
# => ["1. apple", "2. banana"]
Pitfall: Don’t use mappa for side effects only.
ruby
# Returns [nil, nil, nil]
[1, 2, 3].map { |n| puts n }
Ruby Enumerable: select (or find_all) – Filter Matching Items
What select Does
Returns a new array of elements where block returns VERO.
ruby [1, 2, 3, 4].select(&:even?) # => [2, 4]
When to Use Ruby Enumerable select
- Filtering valid records
- Querying data
- Subsetting collections
Ruby Enumerable select Esempi
Passing Scores
ruby
scores = [89, 45, 92, 61]
scores.select { |s| s >= 70 } # => [89, 92]
Active Users
ruby
users = [
{name: "Alice", active: true},
{name: "Bob", active: false}
]
users.select { |u| u[:active] } # => [{name: "Alice", active: true}]
Opposite: reject
ruby [1, 2, 3, 4].reject(&:even?) # => [1, 3]
Ruby Enumerable: Key Differences
| Metodo | Returns | Purpose |
|---|---|---|
ciascuno |
Original collection | Side effects |
mappa |
New array of transformed values | Transform data |
select |
New array of matching elements | Filter data |
Ruby Enumerable: Chaining for Power
Chain methods for expressive pipelines:
ruby
(1..10)
.select(&:even?) # [2, 4, 6, 8, 10]
.map { |n| n ** 2 } # [4, 16, 36, 64, 100]
.each { |sq| puts sq }
Real-world example:
ruby
active_emails = users
.select { |u| u[:active] && u[:age] >= 18 }
.map { |u| u[:email] }
Ruby Enumerable: Performance Tips
One Pass > Two
ruby
# Slower: two iterations
users.map(&:age).select { |a| a > 18 }
# Faster: one iteration
users.select { |u| u[:age] > 18 }.map(&:age)
Symbol-to-Proc Shorthand
ruby names.map(&:upcase)
Lazy Evaluation for Large/Infinite Data
ruby
(1..Float::INFINITY).lazy
.select(&:even?)
.map { |n| n * n }
.first(5)
# => [4, 16, 36, 64, 100]
Ruby Enumerable: Bonus Patterns
Safe Parsing with mappa + compact
ruby
["1", "2", "abc"].map { |s| Integer(s) rescue nil }.compact
# => [1, 2]
Find First Match
ruby
admin = users.find { |u| u[:role] == "admin" } # Better than select.first
Accumulate with each_with_object
ruby
[1, 2, 3].each_with_object({}) { |n, h| h[n] = n * 2 }
# => {1=>2, 2=>4, 3=>6}
Ruby Enumerable: Final Checklist
- Utilizzo
ciascuno→ side effects - Utilizzo
mappa→ transform - Utilizzo
select→ filter - Chain for clarity
- Never ignore return values
- Prefer
findoverselect.first - Utilizzo
lazyfor huge/infinite streams
Conclusione:
The Ruby Enumerable module is more than a collection of methods — it’s a philosophy of clean, readable, and efficient code. By mastering each, map, E select, you gain the ability to:
- Express intent clearly — no more confusing loops.
- Avoid bugs — return values matter, and these methods enforce it.
- Write performant code — one-pass operations and lazy evaluation.
- Chain fluently — build powerful data pipelines in a single line.
A RailsCarma, un'azienda leader Società di sviluppo Ruby on Rails, we apply these principles every day to build scalable, maintainable, and elegant applications. Whether it’s filtering users, transforming datasets, or sending notifications, our developers leverage Ruby’s Enumerable power to write code that’s both expressive and efficient.
Practice these methods daily, chain them wisely, and you’ll soon write Ruby the way it was meant to be written — elegant, expressive, and effortless.
Start today: open your terminal, fire up irb, and experiment with map, select, E ciascuno on any array. The power — and the RailsCarma way — is in your hands.