Ruby: yield block from a block?
Asked Answered
H

2

11

Is it possible for a lambda, proc, method or other type of block in ruby, to yield to another block?
something like...

a = lambda {
  puts 'in a'
  yield if block_given?
}

a.call { puts "in a's block" }

this doesn't work... it just produces

in a
=> nil

Is there way to get the block to call a block?

Heatherheatherly answered 21/10, 2009 at 16:46 Comment(1)
This is still not possible in Ruby 2.7... does anyone know, if Ruby 3 will support such a syntax?Apogee
I
9

I'm not sure if you can you can do that, but something similar would be:

In Ruby 1.8.6:

a = lambda { |my_proc|
  puts 'in a'
  my_proc.call
}

a.call(lambda { puts "in a's block" })

In Ruby 1.9.1, you can have block parameters

a = lambda { |&block|
  puts 'in a'
  block.call
}

a.call { puts "in a's block" }
Ineligible answered 21/10, 2009 at 17:10 Comment(0)
T
8

You can call the block, which is similar to yielding.

a = lambda {|&block| block.call if block}
a.call {print "hello"}

Note that

a.call

Will not return an error.

Tea answered 21/10, 2009 at 17:7 Comment(1)
Not that it's a big deal, but I noticed that you were the first to answer.Subtle

© 2022 - 2024 — McMap. All rights reserved.