First off, no, it wouldn't. I don't want ruby to just say "Hey, maybe this is a string method, let me see if I can run it after running to_s
" on an arbitrary object. That being said, there are two solutions to what you want to do:
If you want to say "On any Author
instance, if someone calls a method that it doesn't have, but that String
does, then it should magically call to_s
", then do this:
class Author < ActiveRecord::Base
def to_s
name
end
def method_missing(s, *a)
x = to_s
if x.respond_to? s then
return x.send(s, *a)
else
super
end
end
end
If you want to say "rjust
on anything that isn't a String should mean calling to_s
first", then:
class Object
def rjust(*a)
to_s.rjust(*a)
end
end
(Repeat with other methods as desired; note that this allows you to do things like 86.rjust(10)
; whether that's a good thing or not may be a matter of taste)