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

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

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

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

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

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

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

  • Converting data types
  • Extracting fields
  • Building new structures

Ruby Enumerable Karte Beispiele

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

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

Ruby Enumerable: wählen (or find_all) – Filter Matching Items

What wählen Does

Returns a new array of elements where block returns wahr.

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

When to Use Ruby Enumerable wählen

  • Filtering valid records
  • Querying data
  • Subsetting collections

Ruby Enumerable wählen Beispiele

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: zurückweisen

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

Ruby Enumerable: Key Differences

Methode Returns Purpose
jede Original collection Side effects
Karte New array of transformed values Transform data
wählen 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 Karte + 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

  • Verwenden Sie jede → side effects
  • Verwenden Sie Karte → transform
  • Verwenden Sie wählen → filter
  • Chain for clarity
  • Never ignore return values
  • Prefer finden over select.first
  • Verwenden Sie faule for huge/infinite streams

Abschluss:

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, Und wählen, 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.

Bei SchienenCarmaeinem führenden Ruby on Rails-Entwicklungsunternehmen, 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 Karte, wählen Sie, Und jede on any array. The power — and the RailsCarma way — is in your hands.

zusammenhängende Posts

Über den Autor des Beitrags

Hinterlasse einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert


de_DEGerman