Array#map

Added in v1.8 · Updated March 13, 2026 · Array Methods
ruby array enumerable

The .map method (also known as .collect) transforms each element in an array by running a block of code for every element and collecting the results into a new array.

numbers = [1, 2, 3, 4, 5]

# Basic usage
squared = numbers.map { |n| n ** 2 }
# => [1, 4, 9, 16, 25]

# collect is an alias for map
doubled = numbers.collect { |n| n * 2 }
# => [2, 4, 6, 8, 10]

Syntax

array.map { |element| block }
array.map do |element|
  # block body
end

# With index
array.map.with_index { |element, index| block }

Parameters

ParameterTypeDefaultDescription
blockBlockRequiredCode to run for each element

What .map Returns

.map always returns a new array. The original array remains unchanged.

original = ["hello", "world"]
uppercased = original.map(&:upcase)

original    # => ["hello", "world"] (unchanged)
uppercased  # => ["HELLO", "WORLD"] (new array)

To modify the original array in place, use .map!, though this is rarely used in practice.

Common Use Cases

Transforming Data

# Convert strings to integers
ages = ["25", "30", "35"].map(&:to_i)
# => [25, 30, 35]

# Extract a specific attribute
users = [{name: "Alice", age: 30}, {name: "Bob", age: 25}]
names = users.map { |u| u[:name] }
# => ["Alice", "Bob"]

With .with_index

fruits = ["apple", "banana", "cherry"]
fruits.map.with_index { |fruit, i| "#{i + 1}. #{fruit}" }
# => ["1. apple", "2. banana", "3. cherry"]

Chaining with Other Methods

# map then select (keep only even results)
(1..10).map { |n| n * 2 }.select { |n| n % 4 == 0 }
# => [4, 8, 12, 16, 20]

# map with compact (remove nils)
[1, 2, nil, 3].map { |n| n&.to_s }
# => ["1", "2", nil, "3"]

Using Symbol#to_proc

Ruby lets you use the &:method shorthand for simple transformations:

# These are equivalent
words.map { |w| w.upcase }
words.map(&:upcase)

numbers.map { |n| n.to_s }
numbers.map(&:to_s)

.map vs .collect

There is no difference between .map and .collect. They are exactly the same method. Use whichever reads better in context:

# map reads well when transforming
results.map { |r| process(r) }

# collect reads well when collecting
results.collect { |r| r[:value] }

Performance Notes

  • .map creates a new array, so for large datasets this uses memory
  • For simple transformations, &:method is slightly faster than a block
  • Use .each when you don’t need the collected results

Gotchas

Forgetting the Return Value

# Common mistake: not using the return value
numbers.map { |n| puts n * 2 }
# => [nil, nil, nil, nil, nil]

# puts returns nil, so map collects nils
# Use each for side effects, map for transformations

map vs flat_map

# map returns array of arrays
[[1, 2], [3, 4]].map { |arr| arr.map { |n| n * 2 } }
# => [[2, 4], [6, 8]]

# flat_map flattens one level
[[1, 2], [3, 4]].flat_map { |arr| arr.map { |n| n * 2 } }
# => [2, 4, 6, 8]

See Also

  • .filter — Select elements matching a condition
  • .flat_map — Map and flatten in one pass