I’m a beginner learning Ruby and I’ve hit something which I can’t find
an explanation for in my text books.
If I run the following code:
class Able < Array
def initialize(contents)
@contents = Array.new(contents)
end
def to_s
“[Able: #{self.join(”, “)}]”
end
end
class Baker
def initialize(contents)
@contents = Array.new(contents)
end
def <<(item)
@contents << item
end
def to_s
“[Baker: #{@contents.join(”, “)}]”
end
end
item = Baker.new([“a”, “b”])
item << Able.new([“c”, “d”])
item << “e”
puts item
I get the following output:
[Baker: a, b, c, d, e]
Clearly the to_s method in my Able class is not being called. If
however I change the definition of Able to:
class Able
def initialize(contents)
@contents = Array.new(contents)
end
def to_s
“[Able: #{@contents.join(”, “)}]”
end
end
(Note that it no longer inherits from Array and instead contains an
array as an instance variable.)
I now get this output (which is what I wanted in the first place).
[Baker: a, b, [Able: c, d], e]
Why when Able is a sub-class of Array does my to_s method get ignored?
TIA,
Joh
P.S. I tried to read the FAQ as instructed first but the link given for
it gives a “Not found” error.