I just found out that ruby seems to treat subclasses of builtin classes
about the same as the builtin classes themselves. For the sake of
performance, ruby many times bypasses normal method call mechanisms for
many
builtin classes (and their subclasses) and effectively inlines the
original
definition. This is kind of frustrating that ruby does this even for
subclasses of builtin classes. Object, Class, Module shouldn’t be a
problem
since they are meant to be subclassed (with some exceptions like
Object#send), but String, Array, immediate classes and probably
others
could be a problem. Of course you can’t even subclass the immediate
classes
anyways.
Here is an example showing the issue when I tried to override the
definition
of #to_s in a subclass of String:
class SubclassedString < String
def to_s
“subclassed:#{super}”
end
end
puts SubclassedString.new(“hello”)
class String
def to_s
“redefined:” + self.to_str
end
end
puts String.new(“hello”)
require ‘delegate’
class DelegatedString < DelegateClass(String)
def initialize(*args)
super(String.new(*args))
end
def to_s
“delegated:#{super}”
end
end
puts DelegatedString.new(“hello”)
Only the DelegatedString does what is expected. Redefining/overriding
#to_s
in String or a subclass of it is pretty much ignored (since the original
definition was inlined in the C code).