Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass more one code block to a function in Ruby?

Tags:

ruby

I don't know any Ruby and am reading some documentationon it now. A doubt I have just after reading about using code blocks and the "yield" keyword is whether it is possible to pass more than one code block to a function, and use both at will from within the called function.

like image 210
jsbueno Avatar asked Nov 25 '09 14:11

jsbueno


1 Answers

You can pass only one block at once but blocks are actually Proc instances and you can pass as many instances you wish as parameters.

def mymethod(proc1, proc2, &block)
  proc1.call
  yield if block_given?
  proc2.call
end

mymethod(Proc.new {}, Proc.new {}) do
  # ...
end

However, it rarely makes sense.

like image 95
Simone Carletti Avatar answered Sep 18 '22 22:09

Simone Carletti