Object#default_to_s
Classes usually override Object#to_s
to provide nice string representations, but what if you really want the default to_s
? Here’s what you can do:
class Object
alias_method(:default_to_s, :to_s)
end
1.default_to_s # => "#<Fixnum:0x3>"
"Tjo".default_to_s # => "#<String:0xb7e376c0>"
Object.new.default_to_s # => "#<Object:0xb7e2fd44>"
Compare the above with this:
1.to_s # => "1"
"Tjo".to_s # => "Tjo"
Object.new.to_s # => "#<Object:0xb7e2fd44>"
class Object
def default_to_s
Object.instance_method(:to_s).bind(self).call
end
end
Slightly cooler, no?