How to Map an Array in Ruby: Simple Guide with Examples
In Ruby, you can use the
map method to transform each element of an array into a new array. It takes a block where you define how to change each item, returning a new array with the results.Syntax
The map method is called on an array and takes a block that specifies how to transform each element. The syntax is:
array.map { |element| transformation }Here, element is each item in the array, and transformation is the code that changes it.
ruby
array.map { |element| element * 2 }
Example
This example shows how to double each number in an array using map. The original array stays the same, and a new array with doubled values is created.
ruby
numbers = [1, 2, 3, 4] doubled = numbers.map { |n| n * 2 } puts doubled.inspect
Output
[2, 4, 6, 8]
Common Pitfalls
A common mistake is using map without a block or forgetting to return the transformed value inside the block. Also, map returns a new array and does not change the original array unless you use map!.
Wrong example (no block):
numbers.map
Right example:
numbers.map { |n| n + 1 }ruby
numbers = [1, 2, 3] # Wrong: no block given # numbers.map # This will raise an error # Right: numbers.map { |n| n + 1 }
Quick Reference
| Method | Description |
|---|---|
| map | Returns a new array with the block's results for each element |
| map! | Modifies the original array with the block's results |
| each | Iterates over elements but returns the original array unchanged |
Key Takeaways
Use
map to create a new array by transforming each element with a block.map does not change the original array unless you use map!.Always provide a block that returns the transformed value for each element.
If you don't need a new array, use
each instead of map.