I encountered the following Ruby code:
class MyClass
attr_accessor :items
...
def each
@items.each{|item| yield item}
end
...
end
What does the each method do? In particular, I don’t understand what yield does.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is an example fleshing out your sample code:
eachloops over a collection. In this case it’s looping over each item in the@itemsarray, initialized/created when I did thenew(%w[a b c d])statement.yield itemin theMyClass.eachmethod passesitemto the block attached tomy_class.each. Theitembeing yielded is assigned to the localy.Does that help?
Now, here’s a bit more about how
eachworks. Using the same class definition, here’s some code:Notice that on the last
nextthe 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.Using
eachwith a block will iterate over the@itemsreceiver and stop when it reaches the last item, avoiding the error, and keeping things nice and clean.