What is the difference between Object.class and Object.class.inspect in Ruby?

Both of these methods seem to return the same result (human readable representation of the object and its type). What are the differences between the methods?

class Foo

end

f = Foo.new
puts f.class          <==  puts Foo
puts f.class.inspect  <==  puts Foo

      

+3


source to share


2 answers


Both of these methods seem to return the same result (human readable representation of the object and its type).

No, they don't.

What is the difference between methods?



Object#class

returns the receiver class.

Module#inspect

is an alias Module#to_s

and returns a string-friendly string representation of the module. In particular, it returns Module#name

, if any, and a unique representation otherwise. For singleton classes, it includes information about the object, which is the singleton class.

So these two methods don't return the same result. In fact, they don't even return the result of the same class: Object#class

returns a class instance Class

, Module#inspect

returns a class instance String

.

+4


source


Since puts

a string is required, it calls the class method to_s

. I believe the class inherits a method from the module :

Returns a string representing this module or class. For base classes and modules, this is the name. For singletons, we show information about what they were attached to.

Also alias: inspect



Perhaps you intended to look at the methods of an object?

class Foo
  def initialize
    @t = 'Junk'
  end
end

f = Foo.new
puts f.class    # =>  Foo
puts f.to_s     # =>  #<Foo:0x007fce2503bbf0>
puts f.inspect  # =>  #<Foo:0x007fce2503bbf0 @t="Junk">

      

0


source







All Articles