Question

In this example from a blog post,

class Array
  def each
    i = 0
    while(i < self.length) do
      yield(self[i])
      i += 1
    end
  end
end

my_array = ["a", "b", "c"]
my_array.each {|letter| puts letter }
# => "a"
# => "b"
# => "c"

Is it necessary to use self in the statement:

yield(self[i])

Or would it be ok to simply say:

yield i
Was it helpful?

Solution

Those are two entirely different things. If you do yield i you will actually yield the number i, which will cause the output to be 1 2 3. The point of the code however is to yield the elements of the array, so you yield self[i], which means "the ith element of the array self", or more technically "call the method [] on self with the argument i and yield the result".

OTHER TIPS

yield(i) would yield a block for index, while yield(self[i]) would yield a block for ith element

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top