Ruby - 可以将块作为参数作为实际块传递给另一个函数吗?
这就是我想要做的:
def call_block(in_class = "String", &block)
instance = eval("#{in_class}.new")
puts "instance class: #{instance.class}"
instance.instance_eval{ block.call }
end
# --- TEST EXAMPLE ---
# This outputs "class: String" every time
"sdlkfj".instance_eval { puts "class: #{self.class}" }
# This will only output "class: Object" every time
# I'm trying to get this to output "class: String" though
call_block("String") { puts "class: #{self.class}" }
在“instance.instance_eval{ block.call }”行上,我试图找到另一种方法来使新实例变量在块上运行实例 eval 。我能想到的唯一方法就是将原始块传递给instance_eval,而不是作为变量或任何东西,而是作为测试示例中的真实块。
有什么建议吗?
This is what I'm trying to do:
def call_block(in_class = "String", &block)
instance = eval("#{in_class}.new")
puts "instance class: #{instance.class}"
instance.instance_eval{ block.call }
end
# --- TEST EXAMPLE ---
# This outputs "class: String" every time
"sdlkfj".instance_eval { puts "class: #{self.class}" }
# This will only output "class: Object" every time
# I'm trying to get this to output "class: String" though
call_block("String") { puts "class: #{self.class}" }
On the line where it says "instance.instance_eval{ block.call }", I'm trying to find another way to make the new instance variable run instance eval on the block. The only way I can think of to get it to do that is to pass instance_eval the original block, not as a variable or anything, but as a real block like in the test example.
Any tips?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。您可以通过在块变量前面添加一个 & 符号来将该块传递给另一个方法,如下所示:
您获得“class: Object”的原因是 Ruby 使用词法作用域。这意味着
puts "class: #{self.class}"
中的 self 引用默认上下文main
。Yes. You can pass the block to the other method by prepending the block variable with an ampersand like so:
The reason your are getting "class: Object" is that Ruby uses lexical scoping. This means that self in
puts "class: #{self.class}"
refers tomain
, the default context.