In ruby, what does "&block" do?

ruby

Solution

`Blocks` give you an opportunity to state a callback to pass on to a method.

The `&` is key here - like @pst mentioned, it "promotes" the block to a Proc and binds the Proc to the variable with the given name.

With `&`

def time(&block)
  puts block
end

time
# => nil
time { foo }
# => #<Proc:0x00029bbc>

Without `&`

def time(block)
  puts block
end

time { foo }
# => ArgumentError: wrong number of arguments (0 for 1)
# Because & isn't included, the method instead expected an arguement,
# but as a block isn't a arguement an error is returned.

Problem

Possible Duplicate: What’s this &block in Ruby? And how does it get passes in a method here? I dont Understand the `&block` part, what does it do? here is an example: ``` def method_missing(method_name, *args, &block) @messages << method_name @object.send method_name, *args, &block end ```

Original source

Related problems