I have an author class:
class Author < ActiveRecord::Base
def to_s
name
end
end
Defining to_s allows me to do puts Author.first, but not puts Author.first.rjust(10):
NoMethodError: undefined method `rjust' for #<Author:0x21eb5d4>
Wouldn’t it be better if Ruby automatically tried to_s before the string method in cases like this? Is there any way to get this behavior?
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
Authorinstance, if someone calls a method that it doesn’t have, but thatStringdoes, then it should magically callto_s“, then do this:If you want to say “
rjuston anything that isn’t a String should mean callingto_sfirst”, then:(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)