Ruby Map and Select
The beginner course walked arrays with each and built new arrays by hand. map, select and reject do those jobs in one line each.
Map builds a new array
map runs the block on each number. The block doubles each number, and map collects the results into a new array.
numbers = [1, 2, 3, 4]
doubled = numbers.map { |n| n * 2 }
p doubledSelect and reject split a list
select keeps the numbers that pass the test. reject keeps the numbers that fail the same test.
numbers = [1, 2, 3, 4, 5, 6]
evens = numbers.select { |n| n.even? }
odds = numbers.reject { |n| n.even? }
p evens
p oddsMap with an index
with_index adds a second block value. The second value counts the items, starting at zero.
names = ["Ana", "Ben", "Cid"]
labels = names.map.with_index { |name, i| "#{i + 1}. #{name}" }
p labelsA chain of select and map
A chain runs the calls from left to right. select first keeps the long words, and map then makes each kept word uppercase.
words = ["cat", "horse", "dog", "elephant"]
result = words.select { |w| w.length > 3 }.map { |w| w.upcase }
p resultExample
prices = [10, 25, 8, 40]
sale = prices.select { |p| p >= 10 }.map { |p| p / 2 }
p saleKey points
- map runs a block on every item.
- map returns a new array of the block results.
- The original array stays unchanged.
- select keeps the items where the block is true.
- reject keeps the items where the block is false.
- map.with_index hands the block each item and its index.
- Calls chain, so select can feed its result into map.
In this example, select keeps the prices of 10 or more. map then halves each kept price. The printed array holds the three sale prices.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does [2, 4, 6].map { |n| n + 1 } return?