tags:

views:

74

answers:

1

It looks like in ruby 1.9.2 if to_s is defined, inspect will return to_s?? Why would this change?

This:

class ToSClass
    def to_s
        "#{self.class.name} to_s called"
    end
end
class InspectClass
    def inspect
        "#{self.class.name} inspect called"
    end
end
class BothClass
    def inspect
        "#{self.class.name} inspect called"
    end
    def to_s
        "#{self.class.name} to_s called"
    end
end

c1 = ToSClass.new
puts c1.inspect
puts c1.to_s
c1 = InspectClass.new
puts c1.inspect
puts c1.to_s
c1 = BothClass.new
puts c1.inspect
puts c1.to_s

outputs this:

ToSClass to_s called
ToSClass to_s called
InspectClass inspect called
#<InspectClass:0x316baf8>
BothClass inspect called
BothClass to_s called
+2  A: 

Object#inspect will call to_s if available. I don't think the behavior has changed.

I've run your program on 1.9.2 and 1.8.7 and don't see any difference.

$ rvm inspect.rb 1.9.2,1.9.1,1.8.7

info: 1.9.2 (ruby-1.9.2-p0): ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-linux] 

ToSClass to_s called
ToSClass to_s called
InspectClass inspect called
#<InspectClass:0x00000001941c80>
BothClass inspect called
BothClass to_s called

info: 1.9.1 (ruby-1.9.1-p378): ruby 1.9.1p378 (2010-01-10 revision 26273) [x86_64-linux] 

ToSClass to_s called
ToSClass to_s called
InspectClass inspect called
#<InspectClass:0x000000011594b8>
BothClass inspect called
BothClass to_s called

info: 1.8.7 (ruby-1.8.7-p302): ruby 1.8.7 (2010-08-16 patchlevel 302) [x86_64-linux] 

ToSClass to_s called
ToSClass to_s called
InspectClass inspect called
#<InspectClass:0x7ffd795afd60>
BothClass inspect called
BothClass to_s called
AboutRuby
Did you mean "I've run your program on 1.9.2 and 1.8.7", or "1.9.2 and 1.9.1"?
Andrew Grimm
I just tested it in 1.8.7 and the results are the same. If only `to_s` is overridden, `inspect` will call that.
Chuck
Oops, I pasted the wrong program output. I'll update that.
AboutRuby
I really need to start using rvm...
jtbandes
I only use RVM for Ruby now. The Ruby installed on the system exists only to get RVM running. It's just too handy.
AboutRuby
Hmmm, jeez, maybe you're right. I started getting this strange error right after switching to 1.9.2 that didn't seem to happen in 1.9.1 where calling puts "x=" + x.inspect was giving a "in `+': can't convert nil into String (TypeError)." The gem was returning nil in to_s sometimes... turns out that's bad... ;) Anyways, thanks for the responses guys.
Travis R