tags:

views:

72

answers:

2

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
+2  A: 

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

Eimantas
+3  A: 

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".

sepp2k
"call the method [] on self with the argument i and return the result" - perfect!
uzo
Actually that should read "and *yield* the result".
sepp2k