Forum: Ruby StackError: stack level too deep

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
10c741d575988433e3fcd04133f3c462?d=identicon&s=25 Sebastian Friedrich (Guest)
on 2006-03-07 20:26
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.
28ca4d5a4133c7c924a7ba464f5fc127?d=identicon&s=25 Brian Mattern (Guest)
on 2006-03-07 20:46
(Received via mailing list)
On Tuesday 07 March 2006 13:26, Sebastian Friedrich wrote:
>   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.
This topic is locked and can not be replied to.