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:
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.
Defining methods
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}"
end9
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: :guestsWhat the program shows:
- Implicit return. A method returns the value of its last expression;
returnis used only to leave early, as inreturn 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:andguests:have no default, so they are required: leaving one out raisesArgumentErrorwith the missing keyword's name.**extrascollects any other keywords into a hash, and*numberscollects 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 ofsort, changing the receiver in place instead of returning a new array, which is whynumbersis unchanged aftersortand changed aftersort!.
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.
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.
# 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}" }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
- bThe ideas, one by one:
yieldruns the block, as many times as the method likes.twiceyields two times. Arguments toyieldbecome the block's parameters (yield b - apasses the gap), and the block's last expression is the value ofyield.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 whatenum_for(:each_gap, items)does. That one line makeseach_gapwork with every method of theEnumerablefamily (next lesson), such asto_a,mapandsum.- Wrapping code.
with_bannerprints something before the block runs, runs it, and prints something after, in anensureclause so that it happens even if the block raises an exception. This "sandwich" pattern is how Ruby manages resources:File.openwith a block closes the file,Mutex#synchronizereleases 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
eachblock adds tototal, 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,_2are numbered parameters (Ruby 2.7) for blocks with several.&:capitalizeturns 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. &blockin a parameter list captures the block as aProcobject, so you can store it or hand it on to another method (items.each(&block)).
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.
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.call16
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)andsquare[6]are three spellings of the same call;.callis the clearest. - Arguments. The proc
shoutaccepts two arguments and ignores the second, and accepts none, gettingnil(whoseto_sis empty, hence"!"). The lambdaaddrefuses one argument. When you store a callable to use later, prefer a lambda: mistakes are reported where they happen. return. Inrun_lambda,return 10leaves only the lambda, and the method goes on to return 20. Inrun_proc,return 10leavesrun_procitself, so 20 is never reached. This is exactly howreturnbehaves inside an ordinary block, which is what makes it possible to writeitems.each { |x| return x if x.ok? }in a search method. Calling a proc whose defining method has already returned, and that containsreturn, raises aLocalJumpError.- Methods as objects.
method(:Integer)returns aMethodobject for an existing method. It responds tocalland to&, so%w[3 1 2].map(&parse)converts each string. - Composition.
f >> gis a new callable that runsfand thengon the result (f << grunsgfirst).:strip.to_proc >> parse >> squarestrips 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_counterhas returned, but the two lambdas it created still share its localcount. Callingincrementthree times changes the valuecurrentreads.
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.
Blocks at work
Here are four patterns you will meet in real Ruby code, each built on what this lesson has covered.
# 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: "?") 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 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
1. Methods, blocks, procs and lambdas
Warm-upComputationalWhat 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
CoreComputationalWhat 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
CoreComputationalWhat 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
CoreComputationalWhat 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
CoreComputationalWhat 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
CoreComputationalWhat does this program print?
counter = 0
add = ->(n) { counter += n }
[1, 2, 3].each(&add)
puts counter
7. Methods, blocks, procs and lambdas
StretchComputationalWhat does puts [1, 2].map do |x| x * 2 end print?
Further reading and resources
- Ruby docs: MethodsDefining methods, arguments of every kind, and return values.
- Ruby docs: Calling methodsPositional, keyword and block arguments at the call site.
- Ruby docs: ProcProcs, lambdas, and the precise differences between them.
- Ruby docs: MethodMethod objects, composition and currying.