Ruby: yield block from a block?

2019-02-09 05:36发布

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?

标签: ruby lambda
2条回答
Anthone
2楼-- · 2019-02-09 05:48

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-02-09 06:02

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" }
查看更多
登录 后发表回答