From: Daniel Schierbeck Date: 2006-07-10T18:45:11+09:00 Subject: Re: Enumberable fails for class Subclass < Array; def enum... Laza wrote: > Array includes Enumerable. But when a subclass of Array redefines > each(), then Enumerable still refers to the original Array.each(). Why > is that? > For example: > > class RangeUnion < Array > def each > super{|x| x.each{|i| yield i} } > end > end > > # u = RangeUnion[1..3, 11..13, "a".."c"] > # u.each{|x| print "#{x} "} # THIS WORKS > # #=> 1 2 3 11 12 13 a b c > # > # u.collect{|x| x} # THIS FAILS!!! > # #=> [1, 2, 3, 11, 12, 13, "a", "b", "c"] # expected > # #=> [1..3, 11..13, "a".."c"] # actual > > In the example above, each() is redefined. But collect() does not use > the redefined each()!!! It uses Array.each(). Subclassing from some > other class works fine: > > class RangeUnion < NotAnArray; ... # gives expected result > > It seems that Enumerable is hardwired (built in) in Array. But subclass > should be able to override it. Why isn't that possible? I've experienced problems myself when trying to redefine some of Enumerable's methods. Apparently Array uses its own #collect and #map methods, plus some others. Maybe if you explicitly re-include Enumerable into your subclass? Cheers, Daniel