Lesson 5 of 10

Blocks and iteration

Goal

The map, select and reduce methods

01

Explanation

A block is a chunk of code you pass to a method, which then runs it on every item, like prices.each { |p| puts p }. The name between the vertical bars is what the current item is called on each pass. You can write a block in two ways: { } for a single line, and do ... end for code that spans several lines.

Most of what you do with arrays relies on blocks: map transforms every item and returns an array of the results, select keeps the items for which the block's condition is true, reject removes them, and reduce combines the whole array into a single value, like reduce(0) { |sum, p| sum + p }. If all the block does is call one method on the item, you can shorten it: prices.reject(&:zero?) means prices.reject { |p| p.zero? }.

Note that each is for doing something with every item, like printing it, and it returns the original array, not the results of the block. So labels = prices.each { |p| "#{p} SAR" } gives you the same numbers back, and the strings are lost without any warning. When you want a new array, use map.

02

Your task

From prices, build the array paid without the free gifts (their price is zero) using reject and the &: shorthand. Then build three values from paid: premium with everything priced 100 or more using select, labels as strings in the form "120 SAR" using map, and total, the sum of the prices, using reduce. Finally, print each string in labels on its own line with each and do ... end.

Checks

6 checks
  1. paid has no free gifts
  2. premium has everything priced 100 or more
  3. labels holds strings, not numbers (map, not each)
  4. total equals 545 and is calculated with reduce
  5. The &: shorthand is used at least once
  6. Each string is printed on its own line
main.rb
OutputRuby 3.4 (ruby.wasm)

Loading Ruby (about 8 MB). This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.