SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Saturday, May 29, 2010

to_s and to _str in ruby

In real life, to_s and to_str usually the return the same value;but they don't have to do so.
There are several differences.First of all any object can be converted into string, since every core class has a to_s method.But to_str is never implemented in core except the string & exception class as per the ruby-doc.to_str is used by methods such as String concat to convert their arguments to a string


In short to_s being explicit conversion whereas to_str as being implicit conversion.The implicit conversion will return the result in the "real string value" of the object;the explicit conversion can be thought of as a "forced" conversion.

class Diff
def to_s
"implicit conversion"
end
def to _str
"forced conversion"
end
end

a=Diff.new

puts a # implicit conversion

puts "Output is " + a # Output is forced conversion

puts "Output is #{a}" # Output is implicit conversion



Now we can define this exactly in our own classes.

*Note: This post is a reference one, thanks to ruby-doc

No comments :

Post a Comment