Created
November 26, 2011 18:28
-
-
Save meineerde/1396097 to your computer and use it in GitHub Desktop.
inspect vs. to_s
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example 1 | |
# "Empty" instance | |
################################################# | |
class Foo; end | |
foo = Foo.new | |
# will be true in 1.8.7 and 1.9.2 as no instance variables are defined | |
foo.inspect == foo.to_s | |
# Example 2 | |
# Instance with instance variable | |
################################################# | |
class Foo | |
def initialize; @foo = "foo"; end | |
end | |
foo = Foo.new | |
# will be false in 1.8.7 and 1.9.2 | |
foo.inspect == foo.to_s | |
# foo.inspect returns: "#<Foo:0x00000100a5e618 @foo=\"foo\">" | |
# foo.to_s returns: "#<Foo:0x00000100a5e618>" | |
# Example 3 | |
# With defined to_s | |
################################################# | |
class Foo | |
def to_s; "Hello from Foo"; end | |
end | |
# will be false in 1.8.7 but true in 1.9.2 | |
foo.inspect == foo.to_s | |
# A call of +to_s+ will be the same obviously, but +inspect+ differs. | |
# 1.8.7: "#<Foo:0x103437db8 @foo=\"foo\">" | |
# 1.9.2: "Hello from Foo" | |
# And all that because of http://redmine.ruby-lang.org/issues/1786 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment