Difference between block and &block in Ruby

ruby

Solution

`block` is just a local variable, `&block` is a reference to the block passed to the method.

def foo(block = nil)
  p block
end

foo # => nil
foo("test") # => test
foo { puts "this block will not be called" } # => nil

def foo(&block)
  p block
end

foo # => nil
foo("test") # => ArgumentError: wrong number of arguments (1 for 0)
foo { puts "This block won't get called, but you'll se it referenced as a proc." }
# => #<Proc:0x0000000100124ea8@untitled:20>

You can also use `&block` when calling methods to pass a proc as a block to a method, so that you can use procs just as you use blocks.

my_proc = proc {|i| i.upcase }

p ["foo", "bar", "baz"].map(&my_proc)
# => ["FOO", "BAR", "BAZ"]

p ["foo", "bar", "baz"].map(my_proc)
# => ArgumentError: wrong number of arguments (1 for 0)

The variable name `block` doesn't mean anything special. You can use `&strawberries` if you like, the ampersand is the key here.

You might find this article helpful.

Problem

Why sometimes I should use block and other times &block inside functions that accept blocks?

Original source