Ruby Enumerable each, map, and select

Master Ruby Enumerable: each, map, and select

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 each:

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: each – Execute Per Item

What each 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 each

  • 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 each expecting a transformed array.

ruby
# Wrong
[1, 2, 3].each { |n| n * 2 } # => [1, 2, 3]

Ruby Enumerable: map (or collect) – Transform Every Item

What map 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 map

  • Converting data types
  • Extracting fields
  • Building new structures

Ruby Enumerable map Exempel

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 map for side effects only.

ruby
# Returns [nil, nil, nil]
[1, 2, 3].map { |n| puts n }

Ruby Enumerable: Välj (or find_all) – Filter Matching Items

What Välj Does

Returns a new array of elements where block returns Sann.

ruby
[1, 2, 3, 4].select(&:even?) # => [2, 4]

When to Use Ruby Enumerable Välj

  • Filtering valid records
  • Querying data
  • Subsetting collections

Ruby Enumerable Välj Exempel

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

Metod Returns Syfte
each Original collection Side effects
map New array of transformed values Transform data
Välj 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 map + 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

  • Användning each → side effects
  • Användning map → transform
  • Användning Välj → filter
  • Chain for clarity
  • Never ignore return values
  • Prefer hitta over select.first
  • Användning lazy for huge/infinite streams

Slutsats:

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, och Välj, 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.

RailsCarmaett ledande Ruby on Rails utvecklingsföretag, 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, och each on any array. The power — and the RailsCarma way — is in your hands.

relaterade inlägg

Om inläggsförfattare

Lämna en kommentar

Din e-postadress kommer inte publiceras. Obligatoriska fält är märkta *


sv_SESwedish