# Difference between map and each?
182
In Ruby, `map` and `each` are two different methods used to iterate over collections such as arrays or hashes. Here's a breakdown of the differences between them:
1. Purpose:
- `each`: The `each` method is used to iterate over a collection and perform an operation for each element. It is primarily used for side effects (such as printing to the console or modifying external variables) and does not produce a new array.
- `map`: The `map` method is used to iterate over a collection, apply a transformation to each element, and return a new array containing the transformed elements.
2. Return Value:
- `each`: Returns the original collection.
- `map`: Returns a new array containing the results of the block's execution.
3. Usage:
- `each`: Typically used when you want to perform some action on each element but do not need to collect the results.
- `map`: Used when you need to transform each element of the collection and collect the results into a new array.
Example
Using `each`:
1. Purpose:
- `each`: The `each` method is used to iterate over a collection and perform an operation for each element. It is primarily used for side effects (such as printing to the console or modifying external variables) and does not produce a new array.
- `map`: The `map` method is used to iterate over a collection, apply a transformation to each element, and return a new array containing the transformed elements.
2. Return Value:
- `each`: Returns the original collection.
- `map`: Returns a new array containing the results of the block's execution.
3. Usage:
- `each`: Typically used when you want to perform some action on each element but do not need to collect the results.
- `map`: Used when you need to transform each element of the collection and collect the results into a new array.
Example
Using `each`:
numbers = [1, 2, 3, 4, 5] numbers.each do |number| puts number * 2 end
Output:
2 4 6 8 10
The original `numbers` array remains unchanged, and `each` returns the original array.
Using `map`:
Using `map`:
numbers = [1, 2, 3, 4, 5] doubled_numbers = numbers.map do |number| number * 2 end puts doubled_numbers
Output:
[2, 4, 6, 8, 10]
The `map` method returns a new array (`doubled_numbers`) containing the results of the block's execution.
In summary, use `each` when you need to iterate over a collection for side effects, and use `map` when you need to transform each element and collect the results.