Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass more than one block to a method in Ruby?

Something like:

def foo(&b1, &b2)
  b1.call
  b2.call
end

foo() { puts "one" } { puts "two" }
like image 937
rui Avatar asked Aug 24 '10 16:08

rui


People also ask

How do you pass block to method in Ruby?

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.

What is difference between block and method in Ruby?

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.

How are arguments passed in 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.

How does yield work in Ruby?

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.


2 Answers

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>
like image 113
Mark Rushakoff Avatar answered Oct 31 '22 16:10

Mark Rushakoff


syntax is a lot cuter in Ruby 1.9:

foo ->{puts :one}, ->{puts :two}
like image 29
horseyguy Avatar answered Oct 31 '22 17:10

horseyguy