Each vs Map in Ruby: Key Differences and Usage
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.
| Aspect | each | map |
|---|---|---|
| Purpose | Iterate for side effects | Iterate to transform and collect results |
| Return value | Original collection | New array with transformed elements |
| Common use case | Printing, modifying external state | Creating new arrays from existing data |
| Modifies original collection? | No (unless explicitly changed) | No, returns new array |
| Chainable? | Yes, but returns original collection | Yes, 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
numbers = [1, 2, 3, 4] numbers.each do |n| puts n * 2 end puts "Returned value: #{numbers.each { |n| n * 2 }}"
map Equivalent
numbers = [1, 2, 3, 4] doubled = numbers.map do |n| n * 2 end puts doubled.inspect puts "Original array: #{numbers.inspect}"
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.each for actions like printing or modifying external state.map when you want to transform data and keep the results.map is chainable and useful for building new collections.