Lesson 14 of 23 · Ruby 4.1 development
Visit, transform and filter
Use each, map and select with blocks to process an array.
Development course: behavior may change with future runtime updates.
The final experiment uses it, introduced in Ruby 3.4. You can also use an explicit block parameter such as |count|.
Learn
An array can pass its entries to a block in order. each is useful when you want an action for every entry, such as printing a label. The block parameter names the current entry.
map builds a new array from the value returned by the block for each entry. select builds a new array containing the original entries for which the block returns a truthy value (anything except false or nil). These methods provide collection operations associated with Enumerable; arrays support them directly.
The plain map and select calls here leave the source array unchanged. Choose the operation by what you need: actions for each entry, transformed entries, or entries that pass a condition.
Calling select and then map lets you filter entries before transforming them. Each method receives its own block. Ruby 3.4 introduced it as the implicit first block parameter when a block declares no parameters and no outer local variable named it takes precedence. The final experiment uses it in two separate blocks.
Example
names = ["Ari", "Bo", "Cam"]
names.each do |name|
puts "Hello, #{name}"
endExperiment
Predict the new array. Change the unit price to 5 and check both the totals and the original quantities.
Predict which stock counts remain. Change the condition to count >= 3 and compare filtering with changing the counts themselves.
Predict which counts reach map. Change the filter to keep counts of at least 3, then change the multiplier to price each remaining group at 5.