I am trying to execute following code:
class Array
def each
for i in self
yield(i)
end
end
end
[1,2,3,4].each {|i| puts i*i}
when i run this code i get following error:
stack level too deep (SystemStackError)
But following code execute successfully:
class Array
def each
yield(self[0])
yield(self[1])
yield(self[2])
yield(self[3])
end
end
[1,2,3,4].each {|i| puts i*i}
Output:
1
4
9
16
for…inuseseachinternally so you’re creating recursion. Try naming your method so it does not clash with a built-in method. - Raphael Schweikerteachon your own, then you are simply cheating. You are basically just calling the built-ineachagain, just in the disguise offor/in. - Jörg W Mittag