Ruby 打印注入 Do 语法

发布于 2024-08-18 19:42:50 字数 295 浏览 8 评论 0原文

为什么下面的代码运行良好

p (1..1000).inject(0) { |sum, i|
    sum + i
}

但是,下面的代码给出了错误

p (1..1000).inject(0) do |sum, i|
    sum + i
end

warning: do not use Fixnums as Symbols
in `inject': 0 is not a symbol (ArgumentError)

他们应该不等价吗?

Why is it that the following code runs fine

p (1..1000).inject(0) { |sum, i|
    sum + i
}

But, the following code gives an error

p (1..1000).inject(0) do |sum, i|
    sum + i
end

warning: do not use Fixnums as Symbols
in `inject': 0 is not a symbol (ArgumentError)

Should they not be equivalent?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

Bonjour°[大白 2024-08-25 19:42:50

使用大括号编写的块绑定到注入方法,这就是您的意图,并且它将正常工作。

但是,封装在 do/end 块中的块将绑定到 p 方法。因此,注入调用没有关联的块。在这种情况下,注入会将参数(在本例中为 0)解释为要在每个对象上调用的方法名称。由于 0 不是一个可以转换为方法调用的符号,这会产生警告。

The block written using the curly braces binds to the inject method, which is what your intention is, and it will work fine.

However, the block that is encapsulated in the do/end block, will bind to the p-method. Because of this, the inject call does not have an associated block. In this case, inject will interpret the argument, in this case 0, as a method name to call on every object. Bacuase 0 is not a symbol that can be converted into a method call, this will yield a warning.

哑剧 2024-08-25 19:42:50

问题出在开头的 p 上。如果你忽略这些,你会发现两者都工作正常:

# Works!
[5, 6, 7].inject(0) do |sum, i| # Correctly binds to `inject`.
  sum + i
end

# Works too!
[5, 6, 7].inject(0) { |sum, i|  # Correctly binds to `inject`.
  sum + i
}

但这行不通:

# Kablammo! "p" came first, so it gets first dibs on your do..end block.
# Now inject has no block to bind to!
p [5, 6, 7].inject(0) do |sum, i|   # Binds to `p` -- not what you wanted.
  sum + i
end

The problem is with the p at the beginning. If you omit these you'll see that both work fine:

# Works!
[5, 6, 7].inject(0) do |sum, i| # Correctly binds to `inject`.
  sum + i
end

# Works too!
[5, 6, 7].inject(0) { |sum, i|  # Correctly binds to `inject`.
  sum + i
}

But this won't work:

# Kablammo! "p" came first, so it gets first dibs on your do..end block.
# Now inject has no block to bind to!
p [5, 6, 7].inject(0) do |sum, i|   # Binds to `p` -- not what you wanted.
  sum + i
end
救星 2024-08-25 19:42:50

这看起来像是 do/end 和括号之间的绑定差异的影响:

如上面使用的括号将绑定到最后一个链接的函数,而 do/end 将绑定到第一个函数。

我认为这是一种奇怪的说法,但基本上第一个实例是将块传递给函数“inject”,而第二个实例实际上试图将块传递给第一个方法“p”。

This looks like a effect of the difference in binding between do/end and brackets:

brackets, used as you are above, will bind to the last function chained while do/end will bind to the first.

I think thats sort of a odd way to say it, but basically the first instance is passing the block to the function 'inject', while the second is actually trying to pass the block to the first method 'p'.

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