Ruby:从块产生收益块? [英] Ruby: yield block from a block?

查看:44
本文介绍了Ruby:从块产生收益块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lambdaprocmethod或其他类型的红宝石块是否有可能屈服于另一个块?
像...

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?

推荐答案

我不确定是否可以做到,但是类似的事情是:

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

在Ruby 1.8.6中:

In Ruby 1.8.6:

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

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

在Ruby 1.9.1中,您可以具有块参数

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" }

这篇关于Ruby:从块产生收益块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆