Skip to content
LumenaryAcademy
Foundations 55 min

Methods, blocks, procs and lambdas

Defining methods with positional and keyword arguments, and Ruby's signature feature, the block, with its relatives the proc and the lambda.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Passing behaviour around

In most languages, a function receives values: numbers, strings, objects. Ruby methods can also receive a piece of behaviour, written right at the call site, almost for free. That piece of code is a block, and it is the single feature that most shapes how Ruby looks:

ruby
5.times { |i| puts i }
File.open("notes.txt") { |file| puts file.readline }
prices.select { |price| price > 100 }

In each line, the method decides when and how often to run the code, and the block decides what to do. times runs it five times; File.open runs it once and closes the file afterwards, even if the block raises an error; select runs it for each element and keeps those for which it returns true. Without blocks, each of these would need a loop, a try/finally, or a separate function written somewhere else.

This lesson starts with ordinary methods and their arguments, then explains blocks in depth, and ends with procs and lambdas, which are blocks turned into objects you can store and pass around.

Worked examplesH

Defining methods

ruby
def area(width, height = width) = width * height

def book_table(name:, guests:, time: "19:00", **extras)
  notes = extras.map { |key, value| "#{key}: #{value}" }.join(", ")
  line = "#{name}, #{guests} guests at #{time}"
  notes.empty? ? line : "#{line} (#{notes})"
end

def stats(*numbers)
  return nil if numbers.empty?

  [numbers.min, numbers.max, numbers.sum.fdiv(numbers.size)]
end

def palindrome?(text)
  letters = text.downcase.delete("^a-z")
  letters == letters.reverse
end

puts area(3), area(3, 4)
puts book_table(name: "Okafor", guests: 4)
puts book_table(guests: 2, name: "Lindqvist", time: "20:30", window: true, cake: "birthday")

low, high, mean = stats(4, 8, 15, 16, 23, 42)
puts "low #{low}, high #{high}, mean #{mean}"
p stats
p palindrome?("Never odd or even"), palindrome?("Ruby")

numbers = [3, 1, 2]
p numbers.sort, numbers
numbers.sort!
p numbers

begin
  book_table(name: "Okafor")
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
text
9
12
Okafor, 4 guests at 19:00
Lindqvist, 2 guests at 20:30 (window: true, cake: birthday)
low 4, high 42, mean 18.0
nil
true
false
[1, 2, 3]
[3, 1, 2]
[1, 2, 3]
ArgumentError: missing keyword: :guests

What the program shows:

  • Implicit return. A method returns the value of its last expression; return is used only to leave early, as in return nil if numbers.empty? (a guard clause, a very common Ruby idiom).
  • Endless methods (Ruby 3.0), def area(width, height = width) = width * height, suit one-expression methods. A default value can refer to earlier parameters.
  • Keyword arguments are named at the call site, in any order. name: and guests: have no default, so they are required: leaving one out raises ArgumentError with the missing keyword's name. **extras collects any other keywords into a hash, and *numbers collects any number of positional arguments into an array.
  • Multiple return values are really one array, which the caller destructures: low, high, mean = stats(…).
  • Naming conventions: palindrome? answers a question; sort! is the "dangerous" version of sort, changing the receiver in place instead of returning a new array, which is why numbers is unchanged after sort and changed after sort!.

Keyword arguments are how idiomatic Ruby avoids mysterious true/false arguments: book_table(name: "Okafor", guests: 4) explains itself. Since Ruby 3.0 they are strictly separated from positional arguments, so a hash passed positionally no longer turns into keywords by accident. If you read older Ruby code that relies on that conversion, it is a common source of upgrade errors. And since Ruby 3.1, when a local variable has the same name as the keyword, you may leave out the value: with local variables name and guests in scope, book_table(name:, guests:) passes them both.

Method visibility and receivers. Methods defined at the top level of a file become private methods of Object, callable from anywhere in that program without a receiver. Inside classes, which come in the next-but-one lesson, you will mark methods private to hide them from outside callers.

ExplanationH

Blocks and yield

Any method call can be followed by a block, written with braces { … } (conventionally for one line) or do … end (for several). The method receives it invisibly and runs it with yield.

ruby
# yield runs the block the caller attached.
def twice
  yield
  yield
end
twice { print "hip " }
puts "hooray"

# Values go into the block through yield, and the block's value comes back.
def each_gap(items)
  return enum_for(:each_gap, items) unless block_given?

  items.each_cons(2) { |a, b| yield b - a }
end
each_gap([1, 4, 9, 16, 25]) { |gap| print gap, " " }
puts
p each_gap([10, 7, 12]).to_a

# A method can run code before and after the caller's block.
def with_banner(title)
  puts "== #{title} =="
  yield
ensure
  puts "== end of #{title} =="
end
with_banner("stock") { puts "  42 crates of mangoes" }

# Blocks are closures: they can read and change the variables around them.
total = 0
[5, 10, 20].each { |n| total += n }
p total

# Short forms: it (Ruby 3.4), numbered parameters, and &:method.
p [1, 2, 3].map { it * 10 }
p [[1, 2], [3, 4]].map { _1 + _2 }
p %w[kigali lima oslo].map(&:capitalize)

# A block can be captured as an object with &block and passed on.
def log_each(items, &block)
  puts "processing #{items.size} items"
  items.each(&block)
end
log_each(%w[a b]) { |x| puts "  - #{x}" }
text
hip hip hooray
3 5 7 9 
[-3, 5]
== stock ==
  42 crates of mangoes
== end of stock ==
35
[10, 20, 30]
[3, 7]
["Kigali", "Lima", "Oslo"]
processing 2 items
  - a
  - b

The ideas, one by one:

  • yield runs the block, as many times as the method likes. twice yields two times. Arguments to yield become the block's parameters (yield b - a passes the gap), and the block's last expression is the value of yield.
  • block_given? tells a method whether it received a block. The Ruby convention for iteration methods is to return an Enumerator when called without one, which is what enum_for(:each_gap, items) does. That one line makes each_gap work with every method of the Enumerable family (next lesson), such as to_a, map and sum.
  • Wrapping code. with_banner prints something before the block runs, runs it, and prints something after, in an ensure clause so that it happens even if the block raises an exception. This "sandwich" pattern is how Ruby manages resources: File.open with a block closes the file, Mutex#synchronize releases the lock, a database library commits or rolls back a transaction.
  • Closures. A block can read and change local variables from the place where it was written: the each block adds to total, which lives outside it. The block carries its surrounding scope with it.
  • Short forms. it (Ruby 3.4) names the single parameter of a short block. _1, _2 are numbered parameters (Ruby 2.7) for blocks with several. &:capitalize turns a symbol into a block that calls that method on each element. Use these for short, obvious blocks; give parameters real names when the block is longer than a line.
  • &block in a parameter list captures the block as a Proc object, so you can store it or hand it on to another method (items.each(&block)).
DefinitionsH

Procs and lambdas

A block is not an object by itself, but it can become one. Ruby has two flavours of "block as an object", both instances of the class Proc:

Definition— Lambda

Created with ->(x) { … } (the "stabby lambda") or lambda { |x| … }. It behaves like a small anonymous method: it checks the number of arguments strictly, and return inside it returns from the lambda itself.

Definition— Proc

Created with proc { |x| … } or Proc.new, and what a captured &block is. It behaves like a block: missing arguments become nil and extra ones are ignored, and return inside it returns from the method where the proc was defined.

ruby
square = ->(x) { x * x }
add = lambda { |a, b| a + b }
shout = proc { |text| "#{text.to_s.upcase}!" }

p square.call(4), square.(5), square[6], add.call(2, 3), shout.call("hello")
p square.lambda?, shout.lambda?

# Procs are relaxed about arguments; lambdas are strict, like methods.
p shout.call("a", "b"), shout.call
begin
  add.call(1)
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end

# return inside a lambda leaves the lambda; inside a proc it leaves the method.
def run_lambda
  -> { return 10 }.call
  20
end

def run_proc
  proc { return 10 }.call
  20
end
p run_lambda, run_proc

# Methods become objects, and callables compose with >> and <<.
parse = method(:Integer)
pipeline = :strip.to_proc >> parse >> square
p pipeline.call("  7 "), %w[3 1 2].map(&parse), [1, 2, 3].map(&square)

# Currying fixes arguments one at a time.
volume = ->(length, width, height) { length * width * height }
floor_2x3 = volume.curry[2][3]
p floor_2x3[4], floor_2x3[10]

# Each closure keeps its own captured variables alive.
def make_counter
  count = 0
  [-> { count += 1 }, -> { count }]
end
increment, current = make_counter
3.times { increment.call }
p current.call
text
16
25
36
5
"HELLO!"
true
false
"A!"
"!"
ArgumentError: wrong number of arguments (given 1, expected 2)
20
10
49
[3, 1, 2]
[1, 4, 9]
24
60
3
  • Calling. square.call(4), square.(5) and square[6] are three spellings of the same call; .call is the clearest.
  • Arguments. The proc shout accepts two arguments and ignores the second, and accepts none, getting nil (whose to_s is empty, hence "!"). The lambda add refuses one argument. When you store a callable to use later, prefer a lambda: mistakes are reported where they happen.
  • return. In run_lambda, return 10 leaves only the lambda, and the method goes on to return 20. In run_proc, return 10 leaves run_proc itself, so 20 is never reached. This is exactly how return behaves inside an ordinary block, which is what makes it possible to write items.each { |x| return x if x.ok? } in a search method. Calling a proc whose defining method has already returned, and that contains return, raises a LocalJumpError.
  • Methods as objects. method(:Integer) returns a Method object for an existing method. It responds to call and to &, so %w[3 1 2].map(&parse) converts each string.
  • Composition. f >> g is a new callable that runs f and then g on the result (f << g runs g first). :strip.to_proc >> parse >> square strips the text, parses it as an integer, and squares it: 49.
  • Currying. volume.curry[2][3] supplies the first two arguments and returns a lambda waiting for the third.
  • Closures keep their variables alive. make_counter has returned, but the two lambdas it created still share its local count. Calling increment three times changes the value current reads.

In everyday Ruby, you will write blocks constantly, lambdas sometimes (for callbacks, strategies, small tables of behaviour such as { "+" => ->(a, b) { a + b } }), and Proc.new almost never.

Worked examplesH

Blocks at work

Here are four patterns you will meet in real Ruby code, each built on what this lesson has covered.

ruby
# 1. A retry helper: the block is the work, the method is the policy.
class FlakyNetwork < StandardError; end

def retrying(attempts:, on: StandardError)
  tries = 0
  begin
    tries += 1
    yield tries
  rescue on => e
    puts "  attempt #{tries} failed: #{e.message}"
    retry if tries < attempts
    raise
  end
end

result = retrying(attempts: 3, on: FlakyNetwork) do |attempt|
  raise FlakyNetwork, "timeout" if attempt < 3

  "weather data (on attempt #{attempt})"
end
puts result

# 2. A hash whose default block computes and remembers missing values.
fib = Hash.new { |memo, n| memo[n] = n < 2 ? n : memo[n - 1] + memo[n - 2] }
puts fib[90]
puts "remembered #{fib.size} values"

# 3. then and tap: blocks in the middle of a chain.
"  Hello, Lagos  "
  .strip
  .tap { |s| puts "after strip: #{s.inspect}" }
  .then { |s| s.length > 10 ? s[0, 10] + "…" : s }
  .then { |s| puts "shortened: #{s}" }

# 4. Forwarding every argument, including the block, with ...
def log_call(name, ...)
  puts "calling #{name}"
  send(name, ...)        # send, because top-level methods are private
end

def greet(who, punctuation: "!") = "Hello, #{who}#{punctuation}"
puts log_call(:greet, "Chidi", punctuation: "?")
text
  attempt 1 failed: timeout
  attempt 2 failed: timeout
weather data (on attempt 3)
2880067194370816120
remembered 91 values
after strip: "Hello, Lagos"
shortened: Hello, Lag…
calling greet
Hello, Chidi?

1. Policy in the method, work in the block. retrying knows how to retry (how many times, which errors count), and the caller's block knows what to do. The block receives the attempt number. The retry keyword, valid inside rescue, jumps back to the start of the begin block; after the last attempt, a bare raise re-raises the same exception so the caller still finds out. Libraries for HTTP clients and background jobs offer helpers with exactly this shape. (Exceptions get a full treatment in the lesson on pattern matching and errors.)

2. A default block on a hash. Hash.new { |memo, n| … } runs the block whenever a missing key is read. Here the block computes a Fibonacci number from two smaller ones and stores it, so each value is computed once: fib[90] returns instantly, having filled in the 91 values from 0 to 90. Without the memo, the same recursion would make an astronomically large number of calls. This is memoisation in one line.

3. tap and then. Both take a block in the middle of a method chain. tap yields the object and returns the same object, which makes it ideal for a debugging print that does not disturb the chain. then yields the object and returns the block's result, so it can transform a value with logic that is not a method of that value.

4. Forwarding with .... A method declared with ... in its parameter list can pass all of its remaining arguments, keyword arguments and block to another method with .... Wrappers, decorators and delegators use it (Ruby 3.2 also added anonymous *, ** and & for forwarding just one kind). The example has to use send rather than public_send, because methods defined at the top level of a file are private, and public_send respects privacy. We ran it with public_send first, and Ruby refused with private method 'greet' called for main (NoMethodError).

Common misconceptionsH

Common misunderstandings

Misconception

"{ … } and do … end are identical." They differ in precedence. puts [1, 2].map { |x| x * 2 } passes the block to map and prints 2 and 4. puts [1, 2].map do |x| x * 2 end passes the block to puts, which ignores it, so map gets no block and returns an Enumerator, and puts prints something like #<Enumerator:0x00007…> (we tried it). Hence the convention: braces for one-line blocks whose value you use, do … end for multi-line blocks.

Misconception

"Methods can see the local variables around them, like blocks can." A def starts a new scope: a method cannot see local variables defined outside it, at the top of the file or anywhere else. Blocks, procs and lambdas can, because they are closures. If you need a value inside a method, pass it as an argument.

Misconception

"return in a block returns from the block." It returns from the method in which the block was written. To give a value back from a block to the method that yields to it, simply make it the last expression, or use next value to finish the current call of the block early.

Misconception

"&:name is magic syntax for map." It works for any method that takes a block. The & converts its operand to a proc by calling to_proc, and Symbol#to_proc makes a proc that calls the named method on its argument. Method objects and lambdas can follow & for the same reason, as map(&parse) showed.

Misconception

"I can define two methods with the same name and different parameters." Ruby has no overloading by argument count or type: a second def with the same name simply replaces the first. Where Java would use several overloads, Ruby uses default values, keyword arguments, *args, or a check on the argument (case value when String … when Integer …). Usually keyword arguments with defaults are the clearest of these.

Exercises

Exercises

1. Methods, blocks, procs and lambdas

Warm-upComputational

What does this program print?

def twice_plus
  a = yield 1
  b = yield 2
  a + b
end
puts twice_plus { |x| x * 10 }

2. Methods, blocks, procs and lambdas

CoreComputational

What does this program print?

def check
  [1, 2, 3].each { |n| return n * 100 if n == 2 }
  0
end
puts check

3. Methods, blocks, procs and lambdas

CoreComputational

What does this program print?

pr = proc { |a, b| "#{a}-#{b}" }
p [pr.call(1), pr.call(1, 2, 3)]

4. Methods, blocks, procs and lambdas

CoreComputational

What does this program print?

double = ->(x) { x * 2 }
inc = ->(x) { x + 1 }
p [(double >> inc).call(5), (double << inc).call(5)]

5. Methods, blocks, procs and lambdas

CoreComputational

What does this program print?

def order(item, qty = 1, size: "M", **rest) = "#{qty}x#{item}/#{size}/#{rest.keys.join}"
puts order("tee", size: "L", gift: true)

6. Methods, blocks, procs and lambdas

CoreComputational

What does this program print?

counter = 0
add = ->(n) { counter += n }
[1, 2, 3].each(&add)
puts counter

7. Methods, blocks, procs and lambdas

StretchComputational

What does puts [1, 2].map do |x| x * 2 end print?

Choose one

Further reading and resources