Menu
Coddy logo textTech

Map and Collect

Part of the Fundamentals section of Coddy's Ruby journey — lesson 68 of 88.

While each is great for performing actions on elements, sometimes you want to transform an array into a new one. The map method (also called collect) does exactly this: it creates a new array containing the results of running your block on each element.

numbers = [1, 2, 3, 4]
doubled = numbers.map { |n| n * 2 }

puts doubled  # Outputs: 2, 4, 6, 8

The key difference from each is that map returns a new array with the transformed values. The original array remains unchanged.

Here's a practical example that converts temperatures from Celsius to Fahrenheit:

celsius = [0, 20, 100]
fahrenheit = celsius.map { |c| c * 9 / 5 + 32 }

puts fahrenheit  # Outputs: 32, 68, 212

You can also use map with strings:

names = ["alice", "bob"]
capitalized = names.map { |name| name.capitalize }

puts capitalized  # Outputs: Alice, Bob

The methods map and collect are identical. Ruby provides both names, so you can use whichever reads better in your code. Most Ruby developers prefer map because it's shorter.

challenge icon

Challenge

Easy

Read a single line of input containing comma-separated integers (e.g., 2,4,6,8,10).

Split the input into an array of integers, then use the map method to create a new array where each number is squared (multiplied by itself).

Print each element of the new squared array on its own line.

For example, if the input is 2,4,6,8,10, the output should be:

4
16
36
64
100

If the input is 1,2,3,4,5, the output should be:

1
4
9
16
25

If the input is 3,7,11, the output should be:

9
49
121

If the input is 10, the output should be:

100

Cheat sheet

The map method (also called collect) transforms an array into a new one by applying a block to each element. It returns a new array with the transformed values, leaving the original array unchanged.

numbers = [1, 2, 3, 4]
doubled = numbers.map { |n| n * 2 }
puts doubled  # Outputs: 2, 4, 6, 8

Example with temperature conversion:

celsius = [0, 20, 100]
fahrenheit = celsius.map { |c| c * 9 / 5 + 32 }
puts fahrenheit  # Outputs: 32, 68, 212

Example with strings:

names = ["alice", "bob"]
capitalized = names.map { |name| name.capitalize }
puts capitalized  # Outputs: Alice, Bob

map and collect are identical methods. Most Ruby developers prefer map.

Try it yourself

# Read the comma-separated input
input = gets.chomp

# TODO: Write your code below
# 1. Split the input string into an array of integers
# 2. Use the map method to square each number
# 3. Print each squared number on its own line
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals