关于理解块和块的基本 Ruby/Rails 问题块变量

发布于 2024-10-19 18:36:37 字数 333 浏览 2 评论 0原文

我开始熟悉 Ruby/Rails,但必须承认,当我看到不熟悉的时,我仍然会怀疑。采用以下代码:

(5..10).reduce(0) do |sum, value|
  sum + value
end

知道它的作用...但是,如何知道传递到 Ruby 块中的参数的顺序?它们是按顺序排列的吗?您如何快速知道它们代表什么?

我假设人们必须查看源代码(或文档)才能发现正在产生的内容......但是有捷径吗?我想我想知道老兽医如何快速辨别一个块正在做什么?!?一种方法应该如何查看/解释块?

I'm starting to get comfortable with Ruby/Rails but must admit I still look askance when I see an unfamiliar block. take the following code:

(5..10).reduce(0) do |sum, value|
  sum + value
end

I know what it does...but, how does one know the order of the parameters passed into a block in Ruby? Are they taken in order? How do you quickly know what they represent?

I'm assuming one must look at the source (or documentation) to uncover what's being yielded...but is there a shortcut? I guess I'm wondering how the old vets quickly discern what a block is doing?!? How should one approach looking at/interpreting blocks?

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

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

发布评论

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

评论(2

挽你眉间 2024-10-26 18:36:37

您只需在文档中查找它,直到记住它为止。我仍然遇到 reduce 和其他几个问题。这就像尝试记住普通方法的参数顺序一样。程序员必须在几乎所有语言中处理这个问题。

You just have to look it up in the documentation until you have it memorized. I still have trouble with reduce and a couple others. It's just like trying to remember the argument order for ordinary methods. Programmers have to deal with this problem in pretty much every language.

许久 2024-10-26 18:36:37

当您编写代码时,除了检查文档之外没有其他方法 - 即使 Ruby 在这类事情上非常一致和连贯,所以通常您只是期望事情以特定的方式工作。
另一方面,当您阅读代码时,您只能希望编码人员足够聪明和友善,能够使用一致的变量名称。在您的示例中,

(5..10).reduce(0) do |sum, value|
  sum + value
end

如果变量被称为 sumvalue 是有原因的! :-) 类似的东西

(5..10).reduce(0) {|i,j|i+j}

当然是相同的,但可读性要差得多。所以这里的教训是:编写好的代码,您将向计算机传达一些信息,而不仅仅是指令!

When you write code, there's no other way than checking the documentation - even if Ruby is quite consistent and coherent in this kind of things, so often you just expect things to work on a particular way.
On the other hand, when you read code, you can just hope that the coder has been smart and kind enough to use consistent variable names. In your example

(5..10).reduce(0) do |sum, value|
  sum + value
end

There is a reason if the variables are called sum and value! :-) Something like

(5..10).reduce(0) {|i,j|i+j}

is of course the same, but much less readable. So the lesson here is: write good code and you'll convey some piece of information more than just instructions to a computer!

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