- Define a method that uses
yield
and awhile
loop to pass each element of a collection to a block. - Gain a deeper understanding of the common iterator
#each
.
Now that you know how the yield
method works, try to write your own version of the #each
method without using the #each
method provided by Ruby.
You'll be building out the content of the #my_each
method. This method should accept an argument of an array and use a while
loop to iterate over each member of that array, yielding each element contained in the array to a block.
Here's an example of what should happen when you call your my_each
method:
collection = [1, 2, 3, 4]
my_each(collection) do |i|
puts i
end
This should output:
1
2
3
4
and return:
#=> [1, 2, 3, 4]
Just like the real #each
method.