什么是“产量"?关键字在Ruby中执行? [英] What does the "yield" keyword do in Ruby?
问题描述
我遇到了以下Ruby代码:
I encountered the following Ruby code:
class MyClass
attr_accessor :items
...
def each
@items.each{|item| yield item}
end
...
end
each
方法有什么作用?特别是,我不理解yield
的作用.
What does the each
method do? In particular, I don't understand what yield
does.
推荐答案
这是充实示例代码的示例:
This is an example fleshing out your sample code:
class MyClass
attr_accessor :items
def initialize(ary=[])
@items = ary
end
def each
@items.each do |item|
yield item
end
end
end
my_class = MyClass.new(%w[a b c d])
my_class.each do |y|
puts y
end
# >> a
# >> b
# >> c
# >> d
each
遍历一个集合.在这种情况下,它循环遍历@items
数组中的每个项目,这些数组是在我执行new(%w[a b c d])
语句时初始化/创建的.
each
loops over a collection. In this case it's looping over each item in the @items
array, initialized/created when I did the new(%w[a b c d])
statement.
yield item
将item
传递给附加到my_class.each
的块.产生的item
被分配给本地y
.
yield item
in the MyClass.each
method passes item
to the block attached to my_class.each
. The item
being yielded is assigned to the local y
.
有帮助吗?
现在,这里有更多关于each
的工作方式的信息.使用相同的类定义,下面是一些代码:
Now, here's a bit more about how each
works. Using the same class definition, here's some code:
my_class = MyClass.new(%w[a b c d])
# This points to the `each` Enumerator/method of the @items array in your instance via
# the accessor you defined, not the method "each" you've defined.
my_class_iterator = my_class.items.each # => #<Enumerator: ["a", "b", "c", "d"]:each>
# get the next item on the array
my_class_iterator.next # => "a"
# get the next item on the array
my_class_iterator.next # => "b"
# get the next item on the array
my_class_iterator.next # => "c"
# get the next item on the array
my_class_iterator.next # => "d"
# get the next item on the array
my_class_iterator.next # =>
# ~> -:21:in `next': iteration reached an end (StopIteration)
# ~> from -:21:in `<main>'
请注意,在最后一个next
上,迭代器从数组末尾掉落.这是 NOT 使用块的潜在陷阱,因为如果您不知道数组中有多少个元素,您可以要求太多项并获得异常.
Notice that on the last next
the iterator fell off the end of the array. This is the potential pitfall for NOT using a block because if you don't know how many elements are in the array you can ask for too many items and get an exception.
将each
与块一起使用将在@items
接收器上进行迭代,并在到达最后一项时停止,从而避免错误并保持环境的整洁.
Using each
with a block will iterate over the @items
receiver and stop when it reaches the last item, avoiding the error, and keeping things nice and clean.
这篇关于什么是“产量"?关键字在Ruby中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!