How to pass another block of function code in Ruby?

I do not know any Ruby, and now I am reading some documentation. I doubt that I just read about the use of blocks of code, and the keyword "yield" is the ability to pass more than one block of code to a function and use it as desired from the called function.

+6
ruby
source share
4 answers

You can transfer only one block at a time, but in reality blocks are Proc instances, and you can transfer as many instances as you want.

 def mymethod(proc1, proc2, &block) proc1.call yield if block_given? proc2.call end mymethod(Proc.new {}, Proc.new {}) do # ... end 

However, this rarely makes sense.

+9
source share

Syntactically, using the yield supports only one code block, which is passed to the function.

Of course, you can pass a function to several other functions or "code block objects" ( Proc objects) and use them, but not just using yield .

+1
source share

You can create Proc objects and transfer them as many as you want.

I recommend reading this page to understand the intricacies of all the various block and closure designs that Ruby has.

+1
source share

You can use the call method, rather than letting handle two separate blocks passed to.

Here's how:

 def mood(state, happy, sad ) if (state== :happy) happy.call else sad.call end end mood(:happy, Proc.new {puts 'yay!'} , Proc.new {puts 'boo!'}) mood(:sad, Proc.new {puts 'yay!'} , Proc.new {puts 'boo!'}) 

You can pass args, for example:

 happy.call('very much') 

arguments work just as you expected in blocks:

 Proc.new {|amount| puts "yay #{amount} !"} 
+1
source share

All Articles