Menu
Coddy logo textTech

Chaining Map

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 22 of 56.

You met map in fundamentals, it builds a new array by transforming each element. Its real power shows when you chain it with select, reject, and friends.

Each method returns an array, so calling another method on the result just keeps going:

numbers = [1, 2, 3, 4, 5]
result = numbers
  .select { |n| n.odd? }
  .map    { |n| n * 10 }
puts result.inspect   # [10, 30, 50]

Read the chain top to bottom: start with numbers, keep odd ones, multiply each by 10. No temporary variables, no loop.

The shortcut &:method_name works whenever the block just calls one method:

["hi", "yo"].map { |s| s.upcase }   # ["HI", "YO"]
["hi", "yo"].map(&:upcase)         # ["HI", "YO"]  (same)

This shorthand is everywhere in Ruby code. Recognize it when you see it.

challenge icon

Challenge

Easy

Read a comma-separated list of words. Print on a single line the words longer than 3 characters, in uppercase, joined with , .

Build it as one chain: select the long ones, map them with &:upcase, then join.

For input hi,hello,yo,coddy,sup, the output is:

HELLO, CODDY

Cheat sheet

Chain array methods — each returns a new array, so you can keep calling methods on the result:

numbers = [1, 2, 3, 4, 5]
result = numbers
  .select { |n| n.odd? }
  .map    { |n| n * 10 }
# [10, 30, 50]

Use &:method_name as a shortcut when a block just calls one method:

["hi", "yo"].map(&:upcase)   # ["HI", "YO"]

Try it yourself

words = gets.chomp.split(",")

# TODO: chain select + map(&:upcase) + join
quiz iconTest yourself

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

All lessons in Logic & Flow