是否有必要在yield(self[i])中引用self
在这个来自博客文章的示例中,
class Array
def each
i = 0
while(i < self.length) do
yield(self[i])
i += 1
end
end
end
my_array = ["a", "b", "c"]
my_array.each {|letter| puts letter }
# => "a"
# => "b"
# => "c"
是否有必要使用self 在声明中:
yield(self[i])
或者简单地说:
yield i
In this example from a blog post,
class Array
def each
i = 0
while(i < self.length) do
yield(self[i])
i += 1
end
end
end
my_array = ["a", "b", "c"]
my_array.each {|letter| puts letter }
# => "a"
# => "b"
# => "c"
Is it necessary to use self
in the statement:
yield(self[i])
Or would it be ok to simply say:
yield i
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是完全不同的两件事。如果你
yield i
,你实际上会产生数字i,这将导致输出为1 2 3。然而,代码的要点是产生数组的元素,所以你产生< code>self[i],这意味着“数组 self 的第 i 个元素”,或者更技术地说,“在self
上调用方法[]
,并使用参数i
并产生结果”。Those are two entirely different things. If you do
yield i
you will actually yield the number i, which will cause the output to be 1 2 3. The point of the code however is to yield the elements of the array, so you yieldself[i]
, which means "the ith element of the array self", or more technically "call the method[]
onself
with the argumenti
and yield the result".yield(i)
会产生索引块,而yield(self[i])
会产生第 i 个元素的块yield(i)
would yield a block for index, whileyield(self[i])
would yield a block for ith element