Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 14 of 23 · Ruby 3.2

Visit, transform and filter

Use each, map and select with blocks to process an array.

Ruby 3.2 does not support the implicit it block parameter introduced in Ruby 3.4. This version uses explicit block parameters.

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. Name each block parameter explicitly, such as |count|. The final experiment uses a separate parameter in each block.

Example

names = ["Ari", "Bo", "Cam"]
names.each do |name|
  puts "Hello, #{name}"
end

Experiment

  • 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.

Explore the official manual

Ruby 3.2.4 · Example

Ready to run

Output

Run the code to see what happens.