0
0
RubyComparisonBeginner · 3 min read

Each vs Map in Ruby: Key Differences and Usage

In Ruby, each iterates over a collection and returns the original collection, mainly for side effects, while map iterates and returns a new array with the results of the block. Use each when you want to perform actions without changing the collection, and map when you want to transform data.
⚖️

Quick Comparison

This table summarizes the main differences between each and map in Ruby.

Aspecteachmap
PurposeIterate for side effectsIterate to transform and collect results
Return valueOriginal collectionNew array with transformed elements
Common use casePrinting, modifying external stateCreating new arrays from existing data
Modifies original collection?No (unless explicitly changed)No, returns new array
Chainable?Yes, but returns original collectionYes, returns new array for further chaining
⚖️

Key Differences

The each method in Ruby is used to loop through elements of a collection like an array or hash. It yields each element to the given block and returns the original collection unchanged. This makes each ideal when you want to perform actions such as printing or updating external variables without creating a new collection.

On the other hand, map (also known as collect) also loops through each element but collects the results of the block into a new array. It returns this new array, leaving the original collection untouched. This is useful when you want to transform data, like converting all strings to uppercase or extracting specific attributes.

In summary, each focuses on side effects and returns the original collection, while map focuses on transformation and returns a new array with the processed elements.

⚖️

Code Comparison

ruby
numbers = [1, 2, 3, 4]
numbers.each do |n|
  puts n * 2
end

puts "Returned value: #{numbers.each { |n| n * 2 }}"
Output
2 4 6 8 Returned value: [1, 2, 3, 4]
↔️

map Equivalent

ruby
numbers = [1, 2, 3, 4]
doubled = numbers.map do |n|
  n * 2
end

puts doubled.inspect
puts "Original array: #{numbers.inspect}"
Output
[2, 4, 6, 8] Original array: [1, 2, 3, 4]
🎯

When to Use Which

Choose each when you want to perform actions for each element without changing the collection, such as printing or updating external variables. Choose map when you want to create a new array by transforming each element, like converting values or extracting data. If you need the results for further processing, map is the better choice; if you only need to perform side effects, each is simpler and clearer.

Key Takeaways

each returns the original collection and is used for side effects.
map returns a new array with transformed elements.
Use each for actions like printing or modifying external state.
Use map when you want to transform data and keep the results.
map is chainable and useful for building new collections.