Transforming lists: map, select & co.
With each you walk through a list and do something with every element. Most of the time, though, you want a result: a new list, a selection, a sum. For that, Ruby has a whole toolbox of methods that all take a block. The most important one is called map: it calls the block for every element and collects the results in a new array:
prices = [4.5, 1.2, 3.0, 2.8]
prices.map { |price| price * 2 }The original stays as it is – map builds a new array, just as long as the old one. The block may contain whatever you like:
animals = ["fox", "cat", "hedgehog"]
animals.map { |animal| "#{animal.capitalize} says hello" }For sifting there's select: it keeps only the elements for which the block gives true. reject does the opposite and throws them out. find looks for the first matching element:
numbers = [3, 8, 12, 5, 7, 10]
p numbers.select { |number| number.even? }
p numbers.reject { |number| number > 6 }
numbers.find { |number| number > 6 }Many methods for evaluating a list take a block, too – it says what matters: count counts, sum adds up, max_by and min_by find the champion, sort_by sorts:
words = ["bacon", "egg", "coffee", "milk"]
p words.count { |word| word.length > 3 }
p words.sum { |word| word.length }
p words.max_by { |word| word.length }
words.sort_by { |word| word.length }Because every one of these methods returns a new result, you can chain them – like on a conveyor belt:
numbers.select { |number| number.even? }.map { |number| number * 10 }.sumRead the chain from left to right: “take the even numbers, multiply each by ten, add everything up.” If the block calls just a single method, there's a shorthand: map(&:upcase) means the same as map { |word| word.upcase }. And questions about the whole list are asked with any? (“at least one?”) and all? (“every one?”):
p words.map(&:upcase)
p words.any? { |word| word.start_with?("c") }
words.all? { |word| word.length > 1 }Hashes can do all of this, too. The block then gets two parameters, key and value – and select returns a hash again:
menu = { "bacon" => 4.5, "egg" => 1.2, "coffee" => 3.0, "toast" => 2.0 }
p menu.select { |dish, price| price < 3 }
p menu.map { |dish, price| "#{dish}: #{price} francs" }
menu.sum { |dish, price| price }A rule of thumb to remember: each for doing, map for transforming, select and reject for sifting, sum, count and max_by for evaluating. All of these methods come from the module Enumerable – what a module is, you'll learn in lesson 45. Its documentation lists dozens more, such as group_by, tally or each_slice.
passed – all scores of 60 or more (with select) – and with_bonus – every passed score plus 5 (with map). Expected are [72, 88, 91, 60] and [77, 93, 96, 65].scores = [72, 45, 88, 91, 30, 60]
# passed = scores.select { ... }
# with_bonus = ...
words: initials – the first letters of all the words as one string ("becmp"); longest – the longest word; by_length – the words sorted by length, shortest first.words = ["bacon", "egg", "coffee", "milk", "pancakes"]
# initials = ... # the first letters, as one string: "becmp"
# longest = ... # the longest word
# by_length = ... # the words sorted by length, shortest first