From: Intransition Date: 2010-04-10T00:01:19+09:00 Subject: Re: Is it possible, a fully general Enumerable#recursive ? On Apr 7, 5:49 pm, Intransition wrote: > For the last couple of days I've been trying to write an Enumerable > method called #recursive. Rather than create a bunch of methods like > #recursive_each, #recursive_map, #recursive_sort, etc. I figured that > it should be possible to create a single #recursive method that > returned an Enumerator, or barring that a Functor, that would handle > any enumerable method, e.g. recursive.each, recursive.map, > recursive.sort, and so on. But I have yet to figure out fully general > solution. Working on this more I currently have the method #visit (see the code below). It almost works, but it has this one issue that makes no sense to me, and I wonder what is going on under the hood in Enumerator for it do this. It has the air of a bug to me --or at least a feature deficiency. Notice: [1, 2, 3, ['a', 'b', 'c'] ].visit{ |x| x.succ } => [2, 3, 4, ["b", "c", "d"]] But using Enumerator: [1, 2, 3, ['a', 'b', 'c'] ].visit.map{ |x| x.succ } => [2, 3, 4, "b", "c", "d"] Why is it flattening the result? Here's the code for #visit: module Enumerable def visit(&block) if block_given? map do |e| e.visit(&block) end else to_enum(:visit) end end end class Object def visit(&block) block.call(self) end end class String # This is needed for Ruby 1.8 def visit(&block) block.call(self) end end