Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

oop

class

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
like image 786
localplutonium Avatar asked Apr 07 '26 19:04

localplutonium


1 Answers

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.

like image 91
Jörg W Mittag Avatar answered Apr 09 '26 07:04

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!