In Ruby, what's the difference between String () and #to_s

String(1.1) == (1.1).to_s => true String(1.1) === (1.1).to_s => true 

Is there a difference between the two methods of coercion? If so, can you demonstrate?

+7
source share
3 answers

docs for the String method say:

Converts arg to String by calling its to_s method.

Thus, in general, they are the same, but there are some differences - although you are unlikely to see them for real. String() checks the class of its parameter, and if it is not String yet, it calls to_s on it. Calling to_s directly means that the method is called independently.

Consider the class:

 class MyString < String def to_s "Overridden to_s method" end end 

The MyString instance MyString already a String object, so passing it as a parameter to String() will do nothing. Calling to_s on it, however, will return the Overridden to_s method .

 1.9.3p286 :010 > m = MyString.new 'my string' => "my string" 1.9.3p286 :011 > o = String.new 'orig string' => "orig string" 1.9.3p286 :012 > String o => "orig string" 1.9.3p286 :013 > String m => "my string" 1.9.3p286 :014 > o.to_s => "orig string" 1.9.3p286 :015 > m.to_s => "Overridden to_s method" 

You hardly need to override to_s in a subclass of String , as it is, in the general case you can consider String() and to_s as the same thing, but it may be useful to know what is going on.

+12
source

They raise various exceptions when they fail:

 bo = BasicObject.new String(bo) TypeError: can't convert BasicObject into String bo.to_s NoMethodError: undefined method `to_s' for #<BasicObject:0x0003efbfd79c10> 
+3
source

String (object) is a Kernel method that calls #to_s on an object

+2
source

All Articles