Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass multiple blocks to method in ruby? [duplicate]

Tags:

closures

ruby

I can pass multiple parameters and at last one block parameter to method. But it shows error when i try to pass more than one block. I want to know how it can be done?

def abc(x, &a)
  x.times { a.call("hello") }
end

abc(3) {|a| puts "#{a} Sana"}
abc(1, &proc{|a| puts "#{a} Sana"})

But below definition gives error

def xyz(x, &a, &b)
  puts x
  a.call
  b.call
end
like image 322
Sandip Ransing Avatar asked Feb 25 '12 14:02

Sandip Ransing


1 Answers

You can use Proc:

def xyz(x, a, &b)
  puts x
  a.call
  b.call
end

xyz(3, Proc.new { puts 'foo' }) { puts 'bar' }

# or simpler

xyz(3, proc { puts 'foo' }) { puts 'bar' }
like image 141
Sony Santos Avatar answered Nov 16 '22 16:11

Sony Santos