# StackError: stack level too deep

**URL:** <https://rubytalk.org/t/stackerror-stack-level-too-deep/25525>\
**Category:** ruby-talk\
**Created:** [7 March 2006 19:26 UTC](https://rubytalk.org/t/stackerror-stack-level-too-deep/25525 "2006-03-07T19:26:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sebastian\_Friedrich](https://avatars.discourse-cdn.com/v4/letter/s/6f9a4e/32.png) [@Sebastian\_Friedrich](https://rubytalk.org/u/Sebastian_Friedrich)\
**Post date:** [7 March 2006 19:26 UTC](https://rubytalk.org/t/stackerror-stack-level-too-deep/25525/1 "2006-03-07T19:26:34Z")

</div>

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  
&nbsp;&nbsp;def each  
&nbsp;&nbsp;for x in self  
&nbsp;&nbsp;&nbsp;&nbsp;yield(x)  
&nbsp;&nbsp;end  
&nbsp;&nbsp;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.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Brian\_Mattern](https://avatars.discourse-cdn.com/v4/letter/b/47e85d/32.png) [@Brian\_Mattern](https://rubytalk.org/u/Brian_Mattern)\
**Post date:** [7 March 2006 19:44 UTC](https://rubytalk.org/t/stackerror-stack-level-too-deep/25525/2 "2006-03-07T19:44:55Z")

</div>

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  
&nbsp;&nbsp;self.each do |x|  
&nbsp;&nbsp;&nbsp;&nbsp;yield(x)  
&nbsp;&nbsp;end  
end

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

> **···**
>
> On Tuesday 07 March 2006 13:26, Sebastian Friedrich wrote:
> 
> > 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  
> > &nbsp;&nbsp;def each  
> > &nbsp;&nbsp;for x in self  
> > &nbsp;&nbsp;&nbsp;&nbsp;yield(x)  
> > &nbsp;&nbsp;end  
> > &nbsp;&nbsp;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.
> 
> --  
> Brian Mattern
