strange inspect behaviour

A

Andy Bogdanov

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"
 
F

Fabian Streitel

[Note: parts of this message were removed to make it a legal post.]

interesting, I didn't know that...
behaves the same on 1.8.7

Greetz!
 
A

Andy Bogdanov

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top