Skip to content

Instantly share code, notes, and snippets.

@meineerde
Created November 26, 2011 18:28
Show Gist options
  • Save meineerde/1396097 to your computer and use it in GitHub Desktop.
Save meineerde/1396097 to your computer and use it in GitHub Desktop.
inspect vs. to_s
# 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