I encountered the following Ruby code:
class MyClass
attr_accessor :items
...
def each
@items.each{|item| yield item}
end
...
end
When you write a method that takes a block, you can use the yield keyword to execute the block.
As an example, each could have been implemented in the Array class like this:
class Array
def each
i = 0
while i < self.size
yield( self[i] )
i = i + 1
end
end
end
MyClass#each takes a block. It executes that block once for each item in the instance's items array, passing the current item as an argument.
It might be used like this:
instance = MyClass.new
instance.items = [1, 2, 3, 4, 5]
instance.each do |item|
puts item
end