Array.map / collect
A method that applies a block to each element of an array and returns the results as a new array. The original array is not modified.
Syntax
# Returns a new array with each element transformed.
array.map { |element| expression }
array.collect { |element| expression } # Alias for map
# Destructive version (modifies the original array in place).
array.map! { |element| expression }
array.collect! { |element| expression }
Method List
| Method | Description |
|---|---|
| map { |e| } | Returns a new array with the block applied to each element. The original array is not modified. |
| collect { |e| } | An alias for map. Behaves exactly the same. |
| map! { |e| } | Replaces each element with the block's return value. A destructive method that modifies the original array in place. |
| collect! { |e| } | An alias for map!. |
Sample Code
numbers = [1, 2, 3, 4, 5]
# Create a new array with each element doubled.
doubled = numbers.map { |n| n * 2 }
puts doubled.inspect # [2, 4, 6, 8, 10]
puts numbers.inspect # [1, 2, 3, 4, 5] (original array is unchanged)
# Convert to strings.
strings = numbers.map { |n| "#{n}th" }
puts strings.inspect # ["1th", "2th", "3th", "4th", "5th"]
# You can also use the &:method_name shorthand with a symbol.
words = ["hello", "world", "ruby"]
upcased = words.map(&:upcase)
puts upcased.inspect # ["HELLO", "WORLD", "RUBY"]
# Use map! to modify the original array.
scores = [60, 70, 80, 90]
scores.map! { |s| s + 5 }
puts scores.inspect # [65, 75, 85, 95]
# Also useful for building a hash.
names = ["Alice", "Bob", "Carol"]
length_map = names.map { |name| [name, name.length] }.to_h
puts length_map.inspect # {"Alice"=>5, "Bob"=>3, "Carol"=>5}
Notes
map is the most commonly used method for transforming arrays. The return value of the block becomes each element of the new array. collect is an alias for map and behaves identically. The Ruby community generally prefers map.
The &:method_name syntax uses the to_proc feature of symbols to concisely call a method on each element. For more details, see Symbol#to_s / to_proc.
With the destructive map!, if the block returns nil, the element is replaced with nil. Be careful to avoid accidentally introducing nil values into your array.
To extract only elements that match a condition, use select / filter / reject. To transform and filter at the same time, use flat_map / filter_map.
If you find any errors or copyright issues, please contact us.