# Redefining/overriding methods in builtin classes AND their s

**URL:** <https://www.ruby-forum.com/t/redefining-overriding-methods-in-builtin-classes-and-their-s/68974>\
**Category:** Ruby\
**Created:** [September 17, 2006, 7:38pm UTC](https://www.ruby-forum.com/t/redefining-overriding-methods-in-builtin-classes-and-their-s/68974 "2006-09-17T19:38:12Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![snowbird122](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/c68b51/32.png) [@snowbird122](https://www.ruby-forum.com/u/snowbird122)\
**Post date:** [September 17, 2006, 7:38pm UTC](https://www.ruby-forum.com/t/redefining-overriding-methods-in-builtin-classes-and-their-s/68974/1 "2006-09-17T19:38:12Z")

</div>

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).
