Ruby - 可以将块作为参数作为实际块传递给另一个函数吗?

发布于 2024-08-26 00:50:42 字数 662 浏览 6 评论 0原文

这就是我想要做的:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜`诱少女 2024-09-02 00:50:42

是的。您可以通过在块变量前面添加一个 & 符号来将该块传递给另一个方法,如下所示:

def foo &blk
  # now, blk is a variable bound to a block object
  bar &blk
end

您获得“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:

def foo &blk
  # now, blk is a variable bound to a block object
  bar &blk
end

The reason your are getting "class: Object" is that Ruby uses lexical scoping. This means that self in puts "class: #{self.class}" refers to main, the default context.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文