1

I have my class


class A
  def to_s
    'string'
  end
  def inspect
    'string'
  end
end

and trying to do something like this


a = A.new
'somestring' + a

Error is "in `+': can't convert A into String (TypeError)"

Is there any way to fix it?

P.S. using 'somestring' + a.to_s isn't an option.

Answer found. to_str method needed.

bUg.
  • 912
  • 9
  • 11
  • 2
    You should post your answer as an actual answer and then accept it, so this question shows up as answered in the questions list. – sepp2k Oct 02 '10 at 18:51

1 Answers1

1

#to_s is for representing an object as a String. In your case, you need to convert the object to a String, because String#+ only deals with Strings. In Ruby, type conversions are done with the three letter form of the to_X methods, i.e. to_int, to_ary, to_hash (someone can't count to three ...), to_str and so on.

So, you need to implement to_str, in order to make that work.

However, you should only implement to_str, if your object actually is a string! If it's something else, you must not implement to_str and rather have the clients explicitly represent it as a string using to_s.

Basically, implementing to_str in Ruby is like inheriting from String in Java: it means that A IS-A String.

As an example, look at which classes in the Ruby core library actually implement the type conversion methods:

  • the only class that implements to_ary, is Array itself,
  • the only class that implements to_hash, is Hash itself and
  • the only class that implements to_str, is String itself.

This should show you that implementing to_str is a very serious matter that should not be undertaken lightly.

The only conversion method that does not have only a trivial no-op implementation, is to_int, which is also implemented by Float and Numeric. And actually, I think that is a mistake, since there is an infinite number of Floats which aren't Integers. And Numeric is a superclass of Integer, so saying that every Numeric IS-A Integer is even more strange.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • Symbol also implements (or implemented) `to_int`. Can't work out if that's a no-op or not. If you're doing `Integer(:yikes)`, that may be [undesired behavior](http://stackoverflow.com/questions/49274/safe-integer-parsing-in-ruby/2551994#2551994)! – Andrew Grimm Oct 11 '11 at 23:51