1
votes

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
1
I think it’s because for…in uses each internally so you’re creating recursion. Try naming your method so it does not clash with a built-in method. - Raphael Schweikert
yes it works if i change 'each' to 'aech' - Amit Singh
If the point of this exercise is to learn how to implement each on your own, then you are simply cheating. You are basically just calling the built-in each again, just in the disguise of for/in. - Jörg W Mittag

1 Answers

0
votes

for loop calls each under the hood.

Reference: