ruby - How to yield 2 blocks in 1 method -
how can yield 2 diferent blocks in same method
the example code:
def by_two(n,a) yield n yield end proc1 = proc {|x| p x * 2} proc2 = proc {|x| x + 100} by_two(10, 300, &proc1, &proc2)
the error such -
main.rb:7: syntax error, unexpected ',', expecting ')' by_two(10, 300, &proc1, &proc2)
any suggestions , wrong? thanks
blocks lightweight way of passing single anonymous procedure method. so, by definition, there cannot 2 blocks passed method. it's not semantically impossible, isn't possible syntactically.
ruby does support first-class procedures in form of proc
s, however, , since objects other object, can pass many of them 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 introduction of lambda literals in ruby 1.9, proc
s syntactically lightweight blocks, there not big difference anymore:
by_two(10, 300, -> x { p x * 2 }, -> x { x + 100 }) # 20 # => 400
Comments
Post a Comment