I am trying to create my own each method for the array class. Code is as follows:
class Array
def my_each
i = 0
while i < self.length
yield(self[i])
i += 1
end
self
end
end
my_each {|i| puts i}
[1,2,3,4].my_each
This seems to me like it should work correctly. However, I am getting the message
"Undefined method my_each for main: Object"
I tried moving the block inside the Array class under the method but then got the following:
"Undefined method my_each for Array Class"
My block and method have the same name so it seems to me like this would be an issue of scope. How exactly do blocks behave with method is being defined within a class? Is it advisable to do something like this or simply include the block directly inside my method?