Strange inspect behaviour

The documentation says “if not overridden, #inspect method uses #to_s to
generate the string”, but it turns out that it’s behavior is more
complicated: if it’s not overridden in some place, it uses #to_s until
the first instance variable assignment, after that it uses Object#to_s


~$ cat > test.rb
class Test
def assign
@var = nil
self
end
def to_s
“instance of Test”
end
end
~$ irb
irb(main):001:0> load ‘test.rb’
=> true
irb(main):002:0> Test.new
=> instance of Test
irb(main):003:0> Test.new.assign
=> #<Test:0x9371320 @var=nil>
irb(main):004:0> RUBY_VERSION
=> “1.9.1”

Is this a bug or it’s supposed to act like that?

interesting, I didn’t know that…
behaves the same on 1.8.7

Greetz!

This code seems to make #inspect behave like it’s described in
documentation
class Object
alias to_s inspect
def inspect() to_s end
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs