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
EasyRead 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, CODDYCheat 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier