Something like:
def foo(&b1, &b2)
b1.call
b2.call
end
foo() { puts "one" } { puts "two" }
In Ruby, methods can take blocks implicitly and explicitly. Implicit block passing works by calling the yield keyword in a method. The yield keyword is special. It finds and calls a passed block, so you don't have to add the block to the list of arguments the method accepts.
The only difference is that method has a name but not block and arguments passed between brackets () to method but in block, arguments passed between pipes ||. How block return values: Actually block returns the value which are returned by the method on which it is called. Example: Ruby.
The arguments passed to the method will be placed as an array. This approach can also be used to indicate that the method will accept any number of arguments but won't do anything with them. The syntax is a little different for variable keyword arguments. The arguments passed to the method will be placed as an hash.
Yield is a keyword in Ruby and when we want to make a call to any block then we can use the yield, once we write the yield inside any method it will assume for a blocking call. There is no limitation for passing a number of arguments to the block from yield statements.
You can't pass multiple blocks in that way, but you can pass multiple proc
or lambda
objects:
irb(main):005:0> def foo(b1, b2)
irb(main):006:1> b1.call
irb(main):007:1> b2.call
irb(main):008:1> end
=> nil
irb(main):009:0> foo(Proc.new {puts 'one'}, Proc.new {puts 'two'})
one
two
=> nil
irb(main):010:0>
syntax is a lot cuter in Ruby 1.9:
foo ->{puts :one}, ->{puts :two}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With