→ Playing with blocks in Ruby, passing blocks, calling blocks → → →
Below is some code that plays with blocks. It shows different methods of passing a block, passing parameter and block, as well as passing variable number of parameters and block. It also shows two different ways of calling a block(using .call and []). Can you predict output of the script?
class BlockShow def a(par, &block) puts "in method a" puts "method called with: #{par}" x = block.call 'param for block' puts "again in method, handling: #{x}" b(block) c(&block) d('1st', '2nd', &block) d(&block) end def b(block) puts "in method b that expects block as param" block.call 'param for block from b' end def c(&block) puts "in method c that expects block as block" block['param for block from c'] end def d(*params, &block) puts "in method d that expects parameters and block" puts "called with #{params.size} parameters" block.call params.join("+") end end BlockShow.new.a('param for object') do |par| puts "in block" puts "block called with: #{par}" "result of block called with #{par}" end
Expected output can be seen below:
in method a method called with: param for object in block block called with: param for block again in method, handling: result of block called with param for block in method b that expects block as param in block block called with: param for block from b in method c that expects block as block in block block called with: param for block from c in method d that expects parameters and block called with 2 parameters in block block called with: 1st+2nd in method d that expects parameters and block called with 0 parameters in block block called with:
Created on 12 May 2009