In Ruby, both `map` and `each` are used to iterate over collections, but they have different purposes and behaviors.
1. **`each`:**
The `each` method is an iterator that allows you to loop through each element of a collection and perform an action with each element. However, `each` doesn't transform or modify the original collection; it's mainly used for its side effects.
```ruby
numbers = [1, 2, 3, 4, 5]
numbers.each do |num|
puts num * 2
end
```
In this example, the `each` loop doubles each element in the `numbers` array and prints the result. The original array remains unchanged.
2. **`map`:**
The `map` method is also an iterator, but it creates a new array by applying a block of code to each element of the original collection. It's used to transform the elements and return a new array.
```ruby
numbers = [1, 2, 3, 4, 5]
doubled_numbers = numbers.map do |num|
num * 2
end
```
In this example, the `map` method doubles each element in the `numbers` array and returns a new array called `doubled_numbers`. The original array remains unchanged.
Here's an example that demonstrates the difference between `each` and `map` using the same output:
```ruby
numbers = [1, 2, 3, 4, 5]
# Using 'each' to print doubled values
numbers.each do |num|
puts num * 2
end
# Using 'map' to create a new array with doubled values
doubled_numbers = numbers.map do |num|
num * 2
end
puts doubled_numbers.inspect
```
In this example, both the `each` loop and the `map` method produce the same output (doubled values of the original numbers), but the key difference is that `each` only performs an action (printing), while `map` transforms the data and creates a new array.
No comments:
Post a Comment