L
Laza
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?
-Laza
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?
-Laza