How to Use map in Ruby: Simple Guide with Examples
In Ruby,
map is a method used on arrays to create a new array by applying a block of code to each element. It returns a new array with the transformed values without changing the original array.Syntax
The map method is called on an array and takes a block that defines how each element should be transformed. The block is enclosed in { } or do...end. The method returns a new array with the results.
- array.map { |element| expression }
- array.map do |element| expression end
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, 5] doubled = numbers.map { |num| num * 2 } puts doubled.inspect puts numbers.inspect
Output
[2, 4, 6, 8, 10]
[1, 2, 3, 4, 5]
Common Pitfalls
One common mistake is expecting map to change the original array. It does not modify the original array but returns a new one. To change the original array, use map!. Another pitfall is forgetting to use a block, which will cause an error.
ruby
arr = [1, 2, 3] # Wrong: expecting original array to change arr.map { |x| x + 1 } puts arr.inspect # Output: [1, 2, 3] # Right: use map! to modify original array arr.map! { |x| x + 1 } puts arr.inspect # Output: [2, 3, 4]
Output
[1, 2, 3]
[2, 3, 4]
Quick Reference
| Method | Description |
|---|---|
| map | Returns a new array with the block applied to each element |
| map! | Modifies the original array by applying the block to each element |
| map.with_index | Gives the element and its index to the block |
Key Takeaways
Use
map to create a new array by transforming each element with a block.map does not change the original array; use map! to modify it.Always provide a block to
map to specify how to transform elements.The block variable represents each element in the array during iteration.
You can use
map.with_index to access element indexes during transformation.