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
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 Proc
s, 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, Proc
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With