localplutonium
localplutonium

Reputation: 260

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

It seems like both of these methods return the same result (a human readable representation of the object and it's type). What is the differences between the methods?

class Foo

end

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

Upvotes: 3

Views: 49

Answers (2)

Kathryn
Kathryn

Reputation: 1607

Since puts needs a string, it calls the class's to_s method. I believe Class inherits the method from Module:

Returns a string representing this module or class. For basic classes and modules, this is the name. For singletons, we show information on the thing we’re attached to as well.

Also aliased as: inspect

Perhaps you intended to look at the object's methods?

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

Upvotes: 0

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369536

It seems like both of these methods return the same result (a human readable representation of the object and it's type).

No, they don't.

What is the differences between the methods?

Object#class returns the class of the receiver.

Module#inspect is an alias of Module#to_s and returns a human-readable string representation of the module. In particular, it returns the Module#name if it has one, and a unique representation otherwise. For singleton classes, it includes information about the object the singleton class is the singleton class of.

So, the two methods don't return the same result. In fact, they don't even return a result of the same class: Object#class returns an instance of the Class class, Module#inspect returns an instance of the String class.

Upvotes: 4

Related Questions