LoginSignup
0
0

More than 5 years have passed since last update.

In Ruby, inspect does not substitute to_s

Posted at

In Python,

class Foo:
  def __repr__(self):
    return 'bar'
foo=Foo()
str(foo) # 'bar'

str(foo) gives 'bar' (both in Py2/Py3). So, if __repr__ is defined and __str__ is not defined, __repr__ is called instead.

However, in Ruby,

class Foo
  def inspect
    'bar'
  end
end
foo=Foo.new
foo.to_s # #<Foo:0x0000....>
p foo # bar
puts foo # #<Foo:0x0000....>

foo.to_s does not give 'bar'. So, if you define inspect, you should also define to_s.

検索用:Rubyではinspectはto_sを代替しない

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0