Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to yield 2 blocks in 1 method

How can I yield two diferent blocks in the same method

the example code:

def by_two(n,a)
    yield n
    yield a
end

proc1 = proc {|x| p x * 2}
proc2 = proc {|x| x + 100}

by_two(10, 300, &proc1, &proc2)

the error is such -

main.rb:7: syntax error, unexpected ',', expecting ')'
by_two(10, 300, &proc1, &proc2)

Any suggestions where and what is wrong? Thanks

like image 810
Andrius Avatar asked Apr 21 '14 09:04

Andrius


1 Answers

Blocks are a lightweight way of passing a single anonymous procedure to a method. So, by definition, there cannot be two blocks passed to a method. It's not just semantically impossible, it isn't even possible syntactically.

Ruby does support first-class procedures in the form of Procs, however, and since those are just objects like any other object, you can pass as many of them as you want:

def by_two(n, a, proc1, proc2)
  proc1.(n)
  proc2.(a)
end

proc1 = proc {|x| p x * 2}
proc2 = proc {|x| x + 100}

by_two(10, 300, proc1, proc2)
# 20
# => 400

Since the introduction of lambda literals in Ruby 1.9, Procs are almost as syntactically lightweight as blocks, so there is not a big difference anymore:

by_two(10, 300, -> x { p x * 2 }, -> x { x + 100 })
# 20
# => 400
like image 117
Jörg W Mittag Avatar answered Oct 11 '22 19:10

Jörg W Mittag