Skip to main content

Programming languages · Intermediate · 20 min

Use blocks, procs and Enumerable in Ruby

By Padding · Updated 18 Nov 2026
Ruby 4.0.10 · ruby:4.0-slim

You will process a day of market orders in Ruby 4.0 with blocks and Enumerable methods, write your own block-taking method, compare procs with lambdas, give a custom collection class every Enumerable method by defining each, and print a short sales report.

On this page

Most Ruby code that handles a list never writes a for loop. It hands a block to a method: orders.select { |order| order.paid }, orders.sum { |order| order.total }. The method decides when and how often to run the block, and the block says what to do with each item. Once that clicks, a large part of Ruby and Rails reads like plain sentences.

In this tutorial you work with eight orders from a market stall: who bought what, how many, at what unit price, and whether they have paid. You filter and total them, group and rank them, write a method of your own that takes a block, store blocks as procs and lambdas, and finally wrap the orders in a class that gains map, select, sort_by and about sixty other methods from one include line. The last script prints a report you could hand to the stall owner.

If you have not installed Ruby yet, follow Hello World in Ruby first. The tutorial uses Ruby 4.0.10, the current stable release at the time of writing; any 4.0 patch release works.

Step 1 · Load the orders into Ruby

Check your Ruby version, then make a practice folder:

Bash
ruby --version
mkdir -p ~/ruby-blocks-demo
cd ~/ruby-blocks-demo

Create orders.rb. It defines an Order value type with Data.define, a list of eight orders, and a small helper that formats an amount as naira with thousands separators:

Bash
cat > orders.rb <<'RUBY'
Order = Data.define(:id, :trader, :item, :qty, :unit_price, :paid) do
  def total = qty * unit_price
end

ROWS = [
  [1, "Amaka", "rice",   3,  1200, true],
  [2, "Bayo",  "beans",  5,   900, true],
  [3, "Amaka", "yam",    2,  2500, false],
  [4, "Chidi", "rice",   1,  1200, true],
  [5, "Bayo",  "rice",   4,  1200, true],
  [6, "Chidi", "pepper", 10,  150, false],
  [7, "Amaka", "beans",  2,   900, true],
  [8, "Bayo",  "yam",    1,  2500, true],
].freeze

ORDERS = ROWS.map { |row| Order.new(*row) }.freeze

def money(amount)
  "NGN #{amount.to_s.gsub(/\B(?=(\d{3})+(?!\d))/, ",")}"
end
RUBY

A few things to notice:

  • Data.define (Ruby 3.2 and later) makes a small immutable class with a reader for each field. The do ... end block after it adds methods to that class, here total, written as a one-line "endless" method.
  • ROWS.map { |row| Order.new(*row) } is your first block in this tutorial. map runs the block once per row and collects what it returns into a new array. *row spreads the six values of the row into the six fields.
  • Prices are whole naira held as integers. Money in floats picks up rounding errors (0.1 + 0.2 is not 0.3), so real systems store the smallest unit, kobo for naira or pesewas for cedis, as an integer. The same code works for any currency if you change the label in money.

Check it worked

Bash
ruby -r ./orders.rb -e 'puts ORDERS.size, ORDERS.first.total, money(24900)'

The output is three lines: 8, 3600 (three bags of rice at 1,200) and NGN 24,900. -r ./orders.rb loads the file before running the code after -e.

Step 2 · Loop, transform and filter with each, map, select, reject and sum

Create basics.rb:

Bash
cat > basics.rb <<'RUBY'
require_relative "orders"

ORDERS.first(3).each do |order|
  puts "#{order.id}: #{order.qty} x #{order.item} for #{order.trader}"
end

totals = ORDERS.map { |order| order.total }
p totals

paid   = ORDERS.select { |order| order.paid }
unpaid = ORDERS.reject { |order| order.paid }
puts "Paid: #{paid.size}, unpaid: #{unpaid.size}"

puts "Takings: #{money(paid.sum { |order| order.total })}"
puts "Owed: #{money(unpaid.sum { |order| order.total })}"
RUBY
ruby basics.rb

Each method treats the block's return value differently, and that is the whole lesson here:

  • each ignores what the block returns. You use it for side effects, such as printing, and it returns the original array.
  • map keeps what the block returns, one result per item.
  • select keeps the items for which the block returns something truthy; reject keeps the rest. In Ruby only false and nil are falsy, so 0 and "" count as true.
  • sum with a block adds up what the block returns, so you do not need a separate map first.

None of these change ORDERS. They build new arrays, which is why the frozen list from orders.rb causes no errors.

Check it worked

The script prints three order lines starting 1: 3 x rice for Amaka, then the totals array [3600, 4500, 5000, 1200, 4800, 1500, 1800, 2500], then Paid: 6, unpaid: 2, Takings: NGN 18,400 and Owed: NGN 6,500. Takings plus owed is 24,900, the day's total from the first step.

Step 3 · Group, count and rank with group_by, tally, each_with_object, sort_by and min_by

Create summary.rb:

Bash
cat > summary.rb <<'RUBY'
require_relative "orders"

puts "-- per trader"
ORDERS.group_by { |order| order.trader }.each do |trader, orders|
  puts "#{trader}: #{orders.size} orders, #{money(orders.sum { |o| o.total })}"
end

puts "-- orders per item"
p ORDERS.map { |order| order.item }.tally

puts "-- quantity per item, biggest first"
qty_by_item = ORDERS.each_with_object(Hash.new(0)) do |order, qtys|
  qtys[order.item] += order.qty
end
qty_by_item.sort_by { |_item, qty| -qty }.each do |item, qty|
  puts "#{item}: #{qty}"
end

puts "-- extremes"
smallest = ORDERS.min_by { |order| order.total }
biggest  = ORDERS.max_by { |order| order.total }
puts "Smallest: order #{smallest.id} (#{money(smallest.total)})"
puts "Biggest: order #{biggest.id} (#{money(biggest.total)})"
RUBY
ruby summary.rb

What each method gives back:

  • group_by returns a hash whose keys are the block's results and whose values are arrays of the items that produced them. Hashes in Ruby keep insertion order, so traders appear in the order they first show up.
  • tally counts equal items and returns a hash of item to count. It takes no block, so you map to the item names first.
  • each_with_object passes the same object, here a hash, into every run of the block and returns it at the end. Hash.new(0) makes missing keys read as 0, so += works on the first sighting of an item.
  • sort_by sorts by whatever the block returns. Returning -qty sorts largest first. Called on a hash, it hands the block each key and value and returns an array of [key, value] pairs. The leading underscore in _item tells readers, and Ruby's warnings, that the value is unused.
  • min_by and max_by return the item itself, not the number the block computed, so you still have the whole order to print.

Check it worked

The per-trader section shows Amaka with NGN 10,400, Bayo with NGN 11,800 and Chidi with NGN 2,700. The tally line is {"rice" => 3, "beans" => 2, "yam" => 2, "pepper" => 1}; Ruby 3.4 and later print spaces around =>, so older tutorials show it without them. Quantities run pepper: 10, rice: 8, beans: 7, yam: 3, and the extremes are order 4 at NGN 1,200 and order 3 at NGN 5,000.

Step 4 · Write a method that takes a block with yield

Every method in Ruby can receive one block, whether it mentions it or not. Inside the method, yield runs that block and returns whatever the block returned. Create big_orders.rb with a method that yields only the orders above a threshold:

Bash
cat > big_orders.rb <<'RUBY'
require_relative "orders"

def each_big_order(orders, threshold)
  return enum_for(:each_big_order, orders, threshold) unless block_given?

  orders.each do |order|
    yield order if order.total >= threshold
  end
end

each_big_order(ORDERS, 4000) do |order|
  puts "Big: order #{order.id} (#{money(order.total)})"
end

ids = each_big_order(ORDERS, 4000).map { |order| order.id }
p ids
RUBY
ruby big_orders.rb

block_given? is true when the caller passed a block. When they did not, the guard returns an Enumerator from enum_for: an object that remembers "call each_big_order with these arguments" and supports map, select, first and the rest. That is how ORDERS.each without a block works too, and why the second call can chain .map.

Now see what happens without that guard. Create no_block.rb:

Bash
cat > no_block.rb <<'RUBY'
require_relative "orders"

def each_paid(orders)
  orders.each { |order| yield order if order.paid }
end

each_paid(ORDERS)
RUBY

Run it:

Bash
ruby no_block.rb

Ruby stops with no block given (yield) (LocalJumpError), because yield had nothing to run.

Check it worked

big_orders.rb prints Big: order 2 (NGN 4,500), Big: order 3 (NGN 5,000) and Big: order 5 (NGN 4,800), then [2, 3, 5] from the block-less call. no_block.rb fails with LocalJumpError instead of printing anything.

Step 5 · Store blocks as procs and lambdas

A block is not an object: it exists only for the call it is attached to. When you want to keep one in a variable, pass it around or call it later, you turn it into a Proc. Ruby has two kinds, made with proc { } and lambda { } (or the shorter ->(x) { }), and they differ in two ways that matter. Create callables.rb:

Bash
cat > callables.rb <<'RUBY'
require_relative "orders"

puts "-- arguments"
loose  = proc   { |item, qty| "#{item}: #{qty.inspect}" }
strict = lambda { |item, qty| "#{item}: #{qty.inspect}" }

puts loose.call("rice")
puts loose.call("rice", 3, 99)
puts strict.call("rice", 3)
begin
  strict.call("rice")
rescue ArgumentError => e
  puts "lambda refused: #{e.message}"
end

puts "-- return"
def check_with_lambda
  rule = lambda { return "from the lambda" }
  rule.call
  "the method carried on"
end

def check_with_proc
  rule = proc { return "the proc ended the method" }
  rule.call
  "this line never runs"
end

puts check_with_lambda
puts check_with_proc

def first_unpaid(orders)
  orders.each do |order|
    return order unless order.paid
  end
  nil
end

puts "First unpaid: order #{first_unpaid(ORDERS).id}"

puts "-- passing a lambda as a block"
levy = ->(amount) { amount * 2 / 100 }
levies = ORDERS.map { |order| order.total }.map(&levy)
p levies
puts "Levy due: #{money(levies.sum)}"
RUBY
ruby callables.rb

The two differences:

  • Arguments. A proc is forgiving like a block: missing arguments become nil and extras are dropped. A lambda checks the count like a method and raises ArgumentError.
  • return. Inside a lambda, return leaves the lambda only, like returning from a method. Inside a proc, return leaves the method the proc was written in. Ordinary blocks behave like procs, which is what makes first_unpaid work: the return inside the each block returns from first_unpaid itself and stops the loop at order 3.

That proc behaviour has a trap. If a proc that contains return is called after its method has already finished, there is nothing left to return from and Ruby raises LocalJumpError. Use lambdas for callables you store and pass around, and keep return inside ordinary blocks for early exits like first_unpaid.

&levy turns the lambda back into a block for map. The & works in both directions: in a call it turns a Proc into a block, and in a method definition (def each(&block)) it captures the block as a Proc. The 2% market levy here is a made-up rate for the example.

Check it worked

The arguments section prints rice: nil, then rice: 3 twice, then lambda refused: wrong number of arguments (given 1, expected 2). The return section prints the method carried on, the proc ended the method and First unpaid: order 3; this line never runs does not appear. The last lines are [72, 90, 100, 24, 96, 30, 36, 50] and Levy due: NGN 498.

Step 6 · Shorten blocks with &:symbol and it

Many blocks only call one method on their argument. Ruby has two short forms for that. Create shorthand.rb:

Bash
cat > shorthand.rb <<'RUBY'
require_relative "orders"

p ORDERS.map(&:item).uniq
p ORDERS.select(&:paid).map(&:id)

p ORDERS.select { it.qty >= 4 }.map { it.id }
p ORDERS.sum { it.qty * it.unit_price }
RUBY
ruby shorthand.rb
  • &:item means "a block that calls item on its argument". The & asks the symbol :item for a Proc through Symbol#to_proc, then passes it as the block. It only works when the block calls a single method with no arguments.
  • it (Ruby 3.4 and later) names the single argument of a block that does not declare one, so { it.qty >= 4 } is { |order| order.qty >= 4 }. Use it for short one-line blocks. When a block grows beyond a line or nests inside another, a real name such as |order| reads better. You may also meet _1, the older numbered form; it means the same thing.

Check it worked

The four lines are ["rice", "beans", "yam", "pepper"], [1, 2, 4, 5, 7, 8], [2, 5, 6] and 24900. The last matches the total from the first step, worked out without the total method.

Step 7 · Make your own collection Enumerable

Array, Hash and Range all get map, select, sort_by, min_by and the rest from one module, Enumerable. Its only requirement is that the class defines each and yields each item to the block. Create order_book.rb, a class that holds orders and can take new ones:

Bash
cat > order_book.rb <<'RUBY'
require_relative "orders"

class OrderBook
  include Enumerable

  def initialize(orders = [])
    @orders = orders.dup
  end

  def <<(order)
    @orders << order
    self
  end

  def each(&block)
    return enum_for(:each) unless block

    @orders.each(&block)
    self
  end
end
RUBY

each(&block) captures the block as a Proc, then hands it straight to the array's own each. Returning self matches what Array#each does. The enum_for guard is the same pattern as in each_big_order: without a block, book.each returns an Enumerator, so you can chain on each itself, as in book.each.with_index(1). Without the guard, book.each would pass no block to the array, throw away the array's Enumerator and return self. Enumerable methods such as each_slice do not need the guard, because they always call each with a block of their own.

Try it with try_book.rb:

Bash
cat > try_book.rb <<'RUBY'
require_relative "order_book"

book = OrderBook.new(ORDERS)
book << Order.new(9, "Chidi", "beans", 3, 900, false)

puts book.count
puts money(book.sum(&:total))
p book.sort_by(&:total).first(3).map(&:id)
p book.min_by(&:total).id
p book.each_slice(4).map { it.size }
p book.include?(ORDERS.first)
p book.respond_to?(:select)
p book.each.with_index(1).map { |order, i| "#{i}:#{order.id}" }.first(2)
RUBY
ruby try_book.rb

You wrote one method, and count, sum, sort_by, first, min_by, each_slice and include? all work. The last line numbers the orders from 1 by chaining with_index(1) on the block-less each, which only works because of the guard. Methods such as select and map return plain arrays, not new OrderBook objects; if you need an OrderBook back, wrap the result with OrderBook.new(...).

Check it worked

The output is 9, NGN 27,600 (the day's 24,900 plus Chidi's new 2,700 order of beans), [4, 6, 7], 4, [4, 4, 1], true, true and ["1:1", "2:2"]. If you see undefined method 'each', check that each is spelt correctly inside the class: Enumerable calls it by name.

Step 8 · Print the report and read Rails code with new eyes

Put it together. Create report.rb:

Bash
cat > report.rb <<'RUBY'
require_relative "order_book"

book = OrderBook.new(ORDERS)
paid, unpaid = book.partition(&:paid)

puts "Market report: #{book.count} orders"
puts "Takings: #{money(paid.sum(&:total))}"
puts "Owed:    #{money(unpaid.sum(&:total))}"
puts

puts "By trader"
book.group_by(&:trader)
    .sort_by { |_trader, orders| -orders.sum(&:total) }
    .each do |trader, orders|
      puts format("  %-6s %d orders  %s", trader, orders.size, money(orders.sum(&:total)))
    end
puts

top_item, top_qty = book.each_with_object(Hash.new(0)) { |order, qtys| qtys[order.item] += order.qty }
                        .max_by { |_item, qty| qty }
puts "Top item by quantity: #{top_item} (#{top_qty})"
puts "Owing: " + unpaid.map { "#{it.trader} (order #{it.id}, #{money(it.total)})" }.join(", ")
RUBY
ruby report.rb

The only new method is partition, which splits a collection in two with one block: items where the block is truthy, then the rest. A line starting with . continues the previous expression, which keeps a long chain readable.

Now look at some typical Rails code:

Ruby
Rails.application.routes.draw do
  resources :orders do
    member { patch :mark_paid }
  end
end

class OrdersController < ApplicationController
  before_action :set_order, only: %i[show mark_paid]

  def index
    @orders = Order.where(paid: false).order(:created_at)
    @owed = @orders.sum(&:total)
  end
end

Every piece is something from this tutorial. routes.draw do ... end is a method that captures its block with &block, as OrderBook#each does, and then runs it against a route mapper object with instance_exec. Inside the block, self is that mapper, which is why resources, member and patch can be called bare, without a receiver. The nested resources :orders do ... end and member { ... } blocks are ordinary blocks the mapper calls while it builds the routing table, and because a block keeps the self of the place it was written, they still talk to the same mapper. before_action :set_order passes a symbol that Rails later turns into a method call. ActiveRecord::Relation, the object Order.where(...) returns, includes Enumerable and defines each, the same move you made in OrderBook, so sum(&:total) and map(&:id) work on query results. One caution carries over: Enumerable methods load every matching row into Ruby first. For a big table, let the database do the work, for example Order.where(paid: false).sum(:qty), which runs as SQL. On a low-end Android phone using a Rails page over prepaid data, that difference shows up as how fast the page loads.

Check it worked

The report reads:

Text
Market report: 8 orders
Takings: NGN 18,400
Owed:    NGN 6,500

By trader
  Bayo   3 orders  NGN 11,800
  Amaka  3 orders  NGN 10,400
  Chidi  2 orders  NGN 2,700

Top item by quantity: pepper (10)
Owing: Amaka (order 3, NGN 5,000), Chidi (order 6, NGN 1,500)

The trader totals add up to the takings plus the amount owed: 11,800 + 10,400 + 2,700 = 24,900.

Step 9 · Clean up

Remove the practice folder. Ruby stays installed:

Bash
cd ~
rm -rf ~/ruby-blocks-demo

Check it worked

ls ~/ruby-blocks-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.