Pass a block to a method (list.each { |x| … }) and run it inside the method with yield. When you need the code as a value you can store or pass around, write a lambda: square = ->(x) { x * x }, then square.call(4). map(&:name) is short for map { |x| x.name }. A proc is a looser lambda: it ignores wrong argument counts, and return inside it returns from the surrounding method.
Where Python and JavaScript pass functions as arguments, Ruby has a built-in slot for one piece of code on every method call: the block. Blocks are what each, map and File.open take, and yield is how your own methods call them. When the code has to become an object, Ruby wraps it in a Proc, which comes in two flavors: the lambda, which behaves like a function, and the plain proc, which behaves like a block. The sections below cover writing methods that take a block, capturing a block with &block, the &:name shortcut and method objects, lambdas with the -> operator, closures and currying, and the two differences between a proc and a lambda, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1Blocks and yieldRecommended
A block is the code between { } or do … end after a method call. Inside the method, yield runs it: arguments to yield become the block's parameters, and the block's last expression comes back as the value of yield. block_given? tells you whether the caller passed one, so the block can be optional. For short blocks, it (Ruby 3.4 and later) and the numbered parameters _1, _2 (Ruby 2.7 and later) save naming the parameter.
# A method can take a block and run it with yield def twice yield yield end twice { puts "Hello" } # yield passes values in and gets the block's result back def with_tax(price) total = yield(price * 0.1) "#{price} + tax = #{total}" end puts with_tax(50) { |tax| 50 + tax } # block_given? lets the block be optional def greet(name) return "Hi, #{name}" unless block_given? yield(name) end puts greet("Ann") puts greet("Bob") { |n| "Welcome back, #{n}!" } # Short block parameters: it (Ruby 3.4+) and _1, _2 p [1, 2, 3].map { it * 10 } p [[1, 2], [3, 4]].map { _1 + _2 } # { } binds to map, do ... end binds to p p [1, 2, 3].map { |n| n * 2 } p [1, 2, 3].map do |n| n * 2 end # yield without a block raises LocalJumpError def needs_block = yield begin needs_block rescue LocalJumpError => e puts "#{e.class}: #{e.message}" end
Output
with_tax yields the tax (5.0) and uses what the block returns, so it prints 50 + tax = 55.0; greet falls back to Hi, Ann when no block comes along. The two map calls look the same but are not: { } attaches to the nearest method, map, while do … end attaches to p, so map gets no block and returns #<Enumerator: [1, 2, 3]:map>. Use braces (or parentheses) when the result goes straight into another call. A bare yield with no block raises LocalJumpError: no block given (yield). Inside a block, next skips to the next item; see skip to the next iteration for next and break.
2Capture a block with &block and pass it on
yield can only run the block during the call. To keep the block for later, or hand it to another method, name it as the last parameter with an &: def initialize(label, &on_click). Ruby turns the block into a Proc object (or nil when there is none), and you run it with .call. Going the other way, & in front of an argument turns a proc back into the block of that call. Since Ruby 3.1 a bare & forwards the block without giving it a name.
# &block turns the block into a Proc object you can keep class Button def initialize(label, &on_click) @label = label @on_click = on_click end def click puts "#{@label} clicked" @on_click&.call(@label) end end save = Button.new("Save") { |label| puts " saving from #{label}" } save.click Button.new("Quiet").click # Pass a block on to another method with & def each_even(numbers, &block) numbers.select(&:even?).each(&block) end each_even([1, 2, 3, 4]) { |n| puts "even: #{n}" } # Ruby 3.1+: an anonymous & forwards the block def each_odd(numbers, &) numbers.reject(&:even?).each(&) end each_odd([1, 2, 3, 4]) { |n| puts "odd: #{n}" } # The captured block is a Proc, or nil without a block def capture(&block) = block blk = capture { |x| x * 2 } p blk.class p blk.lambda? p blk.call(21) p capture
Output
The Save button stored its block and ran it on click, printing saving from Save; the Quiet button got no block, so @on_click is nil and &. skips the call. each_even never runs the block itself: it passes it to each. The last lines show what a captured block is: a Proc whose lambda? is false, which returns 42 when called, and nil when the caller passed no block. A method that only runs the block during the call reads more simply with yield.
3map(&:name) and method objects
The & in map(&:name) is the same operator as in section 2: it turns its argument into the call's block. When the argument is not a proc, Ruby first calls its to_proc, and Symbol#to_proc builds a proc that calls the method of that name on its first argument. So users.map(&:name) means users.map { |u| u.name }. The same trick works for your own methods: method(:shout) returns a Method object, and &method(:shout) passes it as the block.
User = Struct.new(:name, :admin) users = [User.new("Ann", true), User.new("Bob", false)] # &:name is short for { |u| u.name } p users.map(&:name) p users.map { |u| u.name } p users.select(&:admin).map(&:name) # & calls to_proc on the symbol: the proc calls that method upcase = :upcase.to_proc p upcase.call("hi") p %w[a b c].map(&:upcase) # A second block argument becomes the method's argument p [1, 2, 3].inject(&:+) p [1, 2, 3].sum # &method(:name) passes a method as the block %w[one two].each(&method(:puts)) def shout(word) = "#{word.upcase}!" p %w[hi bye].map(&method(:shout)) p ["1", "22"].map(&method(:Integer)) # method(:name) gives a Method object you can call later add_five = 5.method(:+) p add_five.call(3) p add_five.arity
Output
The first two lines print the same ["Ann", "Bob"]. inject(&:+) gives 6 because the proc receives the running total and the next element and calls total.+(n); today sum says it directly, and inject(:+) without the & (common in older answers) works too. &method(:puts) prints each word on its own line, and &method(:Integer) turns ["1", "22"] into [1, 22]. 5.method(:+) is bound to the receiver 5, so calling it with 3 gives 8. The shortcut only covers methods called with no arguments: for map { |s| s.split(",") }, write the block.
4Lambdas, the -> operator and closures
-> is the lambda literal, often called the "stabby lambda": ->(x) { x * x } is the same as lambda { |x| x * x }. A lambda is an object, so you can store it, put it in a hash or pass it to a method as a normal argument, which is how a method takes more than one piece of code. Call it with .call, or the short forms .() and []. Coming from JavaScript: plain square(4) does not work, because square is a variable holding an object, not a method. Like blocks, lambdas are closures: they keep access to the local variables around them.
# -> is the "stabby lambda": a function stored in a variable square = ->(x) { x * x } add = ->(a, b = 1) { a + b } hello = -> { "hello" } # Ways to call it p square.call(4) p square.(4) p square[4] p square === 4 p add.call(2) p add.(2, 5) p hello.call # lambda { } is the older spelling of the same thing cube = lambda { |x| x**3 } p cube.call(2) p cube.lambda? # Lambdas are closures: they see (and change) outer variables count = 0 increment = -> { count += 1 } 3.times { increment.call } p count def make_counter n = 0 -> { n += 1 } end counter = make_counter counter.call p counter.call # A lambda works anywhere a block does, with & p [1, 2, 3].map(&square) # curry fixes some arguments now and the rest later multiply = ->(a, b) { a * b } double = multiply.curry[2] p double[21] p [1, 2, 3].map(&double) # >> composes: square first, then double square_then_double = square >> double p square_then_double.call(3)
Output
All four calls print 16, including square === 4: on a proc, === also calls it, which is what lets a lambda sit in a case/when branch. add.call(2) uses the default b = 1 and prints 3. count ends at 3 because the lambda changed the outer variable, and the counter prints 2 on its second call: its n lives on after make_counter returned. multiply.curry[2] returns a new lambda waiting for the second argument, so double[21] is 42, and square >> double squares 3 then doubles it to 18.
5Proc vs lambda: arguments and return
proc { … } and Proc.new { … } make a plain proc; -> and lambda make a lambda. Both are Proc objects, and lambda? tells them apart. They differ in two ways. A lambda checks its argument count like a method and raises ArgumentError; a proc fills missing parameters with nil, drops extra ones and unpacks a single array argument, the way a block does. And return in a lambda leaves the lambda, while return in a proc leaves the method the proc was written in.
add_lambda = ->(a, b) { "a=#{a.inspect} b=#{b.inspect}" }
add_proc = proc { |a, b| "a=#{a.inspect} b=#{b.inspect}" }
# Arguments: a proc is forgiving, a lambda is strict
puts add_proc.call(1)
puts add_proc.call(1, 2, 3)
puts add_proc.call([1, 2])
begin
add_lambda.call(1)
rescue ArgumentError => e
puts "lambda: #{e.message}"
end
p add_lambda.lambda?
p add_proc.lambda?
# return: in a lambda it leaves the lambda,
# in a proc it leaves the method the proc was made in
def with_lambda
check = ->(n) { return :negative if n < 0 }
check.call(-1)
:end_of_method
end
def with_proc
check = proc { |n| return :negative if n < 0 }
check.call(-1)
:end_of_method
end
p with_lambda
p with_proc
# next leaves only the proc, like return in a lambda
step = proc { |n| next :skipped if n.zero?; n * 10 }
p step.call(0)
p step.call(4)
# Proc.new is the same as proc
p Proc.new { |x| x }.lambda?
Output
The proc accepts one, three or an array of arguments and prints a=1 b=nil, then a=1 b=2 twice; the lambda refuses one argument with wrong number of arguments (given 1, expected 2). with_lambda runs to the end and returns :end_of_method, while the return inside the proc ends with_proc itself, which returns :negative. Use next to return a value from a proc or a block alone. If the method that made a proc has already returned, a return inside the proc has nowhere to go and raises LocalJumpError: unexpected return. When you write the code yourself, choose a lambda; plain procs mostly come from captured blocks.
6Which should you use?
| Method | Is an object | Wrong arg count | Best for |
|---|---|---|---|
| block + yield | No | Ignored | One piece of code per call: most cases |
| def m(&block) | Proc | Ignored | Storing a block or passing it on |
| map(&:name) | Proc (lambda) | Raises | Calling one method on each element |
| ->(x) { … } | Proc (lambda) | Raises | Code stored in a variable or passed as an argument |
| proc { |x| … } | Proc | Ignored | Rarely: return leaves the enclosing method |
| method(:name) | Method | Raises | Passing an existing method with & |
Frequently asked questions
What does map(&:name) mean in Ruby?
It is short for map { |x| x.name }. The & turns its argument into the block of the call; since :name is a symbol, Ruby first calls Symbol#to_proc, which returns a proc that calls name on whatever it receives. It works with any method that takes no arguments: select(&:even?), map(&:upcase), each(&:save).
What is the -> operator called in Ruby?
It is the lambda literal, usually called the stabby lambda. ->(x) { x * 2 } creates the same object as lambda { |x| x * 2 }. Call it with .call(3), .(3) or [3], not with (3) alone.
When should I use a lambda and when Proc.new?
Use a lambda (->) whenever you write a function as a value: it checks its arguments and return behaves as in a method. Proc.new and proc make a proc that ignores wrong argument counts and whose return leaves the enclosing method, which is rarely what you want. You mostly meet plain procs as captured blocks (&block).
What is the difference between a block and a proc?
A block is syntax, not an object: the { } or do ... end part of one method call, run with yield. A proc is an object you can store, pass and call many times. &block in a method definition turns the block into a proc, and &my_proc in a call turns a proc back into a block.
Can a Ruby method take more than one block?
No, each call has one block slot. Pass the extra pieces of code as lambdas in normal arguments, for example def run(on_success, on_error) called as run(-> { puts "ok" }, ->(e) { warn e.message }). Inside, call them with .call.
How do I return a value from a block?
The last expression of a block is its value, so usually you write nothing. To leave early, use next value: [1, 2, 3].map { |x| next 0 if x == 2; x } gives [1, 0, 3]. break value stops the loop and makes it the method's result: [1, 2, 3].each { |x| break x * 10 if x == 2 } returns 20. return inside a block returns from the method that contains the block.
Why do I get LocalJumpError?
Two common cases. Calling yield when the caller passed no block raises LocalJumpError: no block given (yield); check block_given? first. And a proc whose return runs after the method that created it has finished raises LocalJumpError: unexpected return; use a lambda, or next, instead.