From: Nasir Khan Date: 2007-08-14T11:59:52+09:00 Subject: Re: to_str behavior ------=_Part_55141_4239912.1187060395577 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Thanks to all the respondents. The confusion stemmed from some of the inconsistency that is around the to_str usage within Ruby. See this below. class A def to_str "hello" end def to_s "bye" end end # Note to_s and to_str return different strings. irb(main):018:0> "xyz"+A.new => "xyzhello" Good, as to_str is called when it is 'expected' that arg to + is going to be a string. irb(main):019:0> "hello" == A.new => false This is fine too as David pointed out, one could argue though because there already is a equal? but anyway....lets move on. Then see irb(main):020:0> A.new.upcase NoMethodError: undefined method `upcase' for hello:A from (irb):20 Again since A.new is not a String a method_missing is called etc. Bear with me a little more :-) irb(main):021:0> "hellooo".include? A.new => true This is good because the argument is expected to be a string. Now see this irb(main):022:0> "a" << A.new => "ahello" OK so now Ruby used the string representation from to_str *not* to_s Now is it true that *only* object of class String are expected to be appended to a string using << operator, hence the coercion? Not quite - irb(main):023:0> "a" << 1 => "a\001" While of course - irb(main):025:0> 1.to_str NoMethodError: undefined method `to_str' for 1:Fixnum But of course - irb(main):038:0> 1.to_s => "1" So is it the case that when a string is "expected" then a to_str is tried if not found then to_s is tried, as can be deduced from the last two operations above? But then of course the following would fail - class B def to_s "hello" end end irb(main):052:0* "bye"+B.new TypeError: can't convert B into String from (irb):52:in `+' from (irb):52 from :0 Now one could rationalize each behavior in isolation but isnt there an inconsistency? Thanks Nasir On 8/13/07, Stefan Rusterholz wrote: > > Nasir Khan wrote: > > Hi, > > I have two related questions on to_str behavior. AFAIK to_str does > > automatic > > coercion to string wherever one is required, it is to be provided for > > objects that exhibit string like behavior. But this mental model did not > > match up with my test - > > class StringLike > include Comparable > def initialize(val) > @val = val > end > def <=>(other) > @val <=> other.to_str > end > def to_str > @val > end > end > > x = StringLike.new("hi") > x == "hi" #=> true > "hi" == x #=> true > > That's from one of my older experiments. I don't remember the reasons. > Feel free to examine why it works with <=> + Comparable. > HTH. > > Regards > Stefan > -- > Posted via http://www.ruby-forum.com/. > > ------=_Part_55141_4239912.1187060395577--