StackError: stack level too deep

  • Thread starter Sebastian Friedrich
  • Start date
S

Sebastian Friedrich

i'm currently learning Ruby. So, while learning about code blocks and
yields i wanted to put my freshly acquired knowledge to the test and
(just to see if i understood correctly) write my own simple each method
for Arrays. so i did:

class Array
def each
for x in self
yield(x)
end
end
end

But running it gives me SystemStackError: stack level too deep. It works
fine when i rename it, so i guess it's just Ruby not appreciating my
fine work or somehow making sure i don't introduce flagrant overwrites
to built-in methods??? Anybody feels like enlightening me on how this
works? Thanks.
 
B

Brian Mattern

i'm currently learning Ruby. So, while learning about code blocks and
yields i wanted to put my freshly acquired knowledge to the test and
(just to see if i understood correctly) write my own simple each method
for Arrays. so i did:

class Array
def each
for x in self
yield(x)
end
end
end

But running it gives me SystemStackError: stack level too deep. It works
fine when i rename it, so i guess it's just Ruby not appreciating my
fine work or somehow making sure i don't introduce flagrant overwrites
to built-in methods??? Anybody feels like enlightening me on how this
works? Thanks.

If I'm not mistaken, the "for foo in bar" construct uses the each method. (It
basically gets translated to "bar.each do |foo|"

So, your method now looks like:

def each
self.each do |x|
yield(x)
end
end

This keeps recursing until ruby kills it due to the stack being too deep.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top