我遇到了以下Ruby代码:
class MyClass
attr_accessor :items
...
def each
@items.each{|item| yield item}
end
...
end
each
法有什么作用?尤其是,我不明白yield
是做什么的.
我遇到了以下Ruby代码:
class MyClass
attr_accessor :items
...
def each
@items.each{|item| yield item}
end
...
end
each
法有什么作用?尤其是,我不明白yield
是做什么的.
下面是一个充实示例代码的示例:
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])
语句时初始化/创建了@items
array.
MyClass.each
方法中的yield item
将item
传递给连接到my_class.each
的块.正在生成的item
被分配给本地y
.
这有用吗?
现在,这里有更多关于each
的工作原理.使用相同的类定义,下面是一些代码:
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使用块的潜在trap ,因为如果你不知道数组中有多少元素,你可能会要求太多的项,并得到一个异常.
将each
与块一起使用将在@items
接收器上迭代,并在到达最后一项时停止,从而避免错误,并保持整洁.