关于理解块和块的基本 Ruby/Rails 问题块变量
我开始熟悉 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需在文档中查找它,直到记住它为止。我仍然遇到
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.当您编写代码时,除了检查文档之外没有其他方法 - 即使 Ruby 在这类事情上非常一致和连贯,所以通常您只是期望事情以特定的方式工作。
另一方面,当您阅读代码时,您只能希望编码人员足够聪明和友善,能够使用一致的变量名称。在您的示例中,
如果变量被称为
sum
和value
是有原因的! :-) 类似的东西当然是相同的,但可读性要差得多。所以这里的教训是:编写好的代码,您将向计算机传达一些信息,而不仅仅是指令!
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
There is a reason if the variables are called
sum
andvalue
! :-) Something likeis 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!