Problems inside the block / lambda

I have the following Ruby code:

# func1 generates a sequence of items derived from x # func2 does something with the items generated by func1 def test(x, func1, func2) func1.call(x) do | y | func2.call(y) end end func1 = lambda do | x | for i in 1 .. 5 yield x * i end end func2 = lambda do | y | puts y end test(2, func1, func2) # Should print '2', '4', '6', '8', and '10' 

This does not work, of course.

 test.rb:11: no block given (LocalJumpError) from test.rb:10:in `each' from test.rb:10 from test.rb:4:in `call' from test.rb:4:in `test' from test.rb:20 
+8
yield ruby lambda block
source share
4 answers

Lambdas does not imply accepting blocks, as regular methods do, so your func1 cannot yield. Do this instead:

 func1 = lambda do |x, &blk| for i in 1 .. 5 blk.call(x * i) end end 

In particular, I believe that this is due to the fact that yield will return control back to the caller block, which will not include lambda calls. Thus, the following code works as you expect:

 def foo (lambda { |n| yield(n) }).call(5) end foo { |f| puts f } # prints 5 
+12
source share

Only in Ruby 1.9:

 func1 = lambda do |x, &blk| for i in 1..5 blk.call(x*i) end end 
+4
source share
 def test(x, func1, func2) func1.call(x) do | y | func2.call(y) end end #change func1 to a method def func1 x for i in 1 .. 5 yield x * i end end #func2 may be either a method or a lambda #I changed it for consistency, but you don't have to def func2 y puts y end test(2, method(:func1), method(:func2)) 
+1
source share

Based on Nikita Misharin, answer here: [ / questions / 652246 / in-ruby-can-you-use-the-lambda-or-or-proc-call-method-to-invoke-an-iterator / 2563620 # 2563620 , I like it:

 def iterator(x) for i in 1 .. 5 yield x * i end end iteratorWrapper = -> (m,&block) { iterator(m) {|n| block.call n} } iteratorWrapper.call(2) { |y| puts y } 

It answers my question here [ In Ruby, can you use the lambda or Proc invocation method to invoke the iterator? .

By wrapping the iterator, it can be arbitrarily passed to other methods and iterating over their blocks.

0
source share

All Articles