From: Josh Cheek Date: 2010-12-02T00:01:28+09:00 Subject: Re: Object#each ? --001636c596cbf4147504965a938f Content-Type: text/plain; charset=ISO-8859-1 On Wed, Dec 1, 2010 at 8:30 AM, Andrew Wagner wrote: > > This is a method that either works on a collection or on single item. As > > soon as a you make Object behave like Enumerable, this breaks and leads > > to recursion. > > > > Well, sure. The whole point is to write, instead of the above: > > def do_sth_on(this) > this.each do > #whatever > end > end > I think he means that you remove the base case that recursive functions may be relying on. Here is an example: # a function, maybe in a lib you are using, # silently doing its job, you don't even know its there # to do its job it must recursively traverse enumerable objects # in this example, it just prints them out def print_nested(iteratable) iteratable.each do |*objects| if objects.size > 1 print_nested(objects) next end object = objects.first if object.respond_to? :each print_nested object else puts object end end end # prints 1 through 16 print_nested [ 1,2,[3,4,[5]], { 6 => 7, 8 => [ 9 , 10 , { 11 => 12..14 } ] }, "15\n16", ] # make everything respond to each class Object def each yield self end end # stack overflow print_nested [ 1,2,[3,4,[5]], { 6 => 7, 8 => [ 9 , 10 , { 11 => 12..14 } ] }, "15\n16", ] --001636c596cbf4147504965a938f--