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.
My nearest success thus far is:
require 'facets/functor'
module Enumerable
def recursive
Functor.new do |op,*a,&b|
__send__(op) do |e|
if self.class === e
e.recursive.__send__(op,*a,&b)
else
b.call(e)
end
end
end
end
end
This works for #each and #map but not #sort.
Can anyone think of a better solution?