0

When I create an object of the class in ruby, the console returns a Hex code. What is the significance of this hex code?

apple = Fruits.new => #Fruits:0x00005569446a55d8

1 Answers1

2

I'm assuming you're running this in irb, or some sort of interactive console. In this scenario inspect is used to display a representation of apple. If you haven't defined your own inspect in the Fruits class, then it's inherited from Object.

inspect → string

Returns a string containing a human-readable representation of obj. The default inspect shows the object's class name, an encoding of its memory address, and a list of the instance variables and their values (by calling inspect on each of them). User defined classes should override this method to provide a better representation of obj. When overriding this method, it should return a string whose encoding is compatible with the default external encoding.

[ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
Time.new.inspect                 #=> "2008-03-08 19:43:39 +0900"

class Foo
end
Foo.new.inspect                  #=> "#<Foo:0x0300c868>"

class Bar
  def initialize
    @bar = 1
  end
end
Bar.new.inspect                  #=> "#<Bar:0x0300c868 @bar=1>"
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • yes, I am using IRB, the Hex code you get when you create object like this #=> "#". what is the significance of this, is this object_id or something else? – Gaurav Sharma May 09 '22 at 17:46
  • Quote from [the docs](https://ruby-doc.org/core-3.1.2/Object.html#method-i-inspect): _Returns a string containing a human-readable representation of obj. The default inspect shows the object's class name, an encoding of its memory address, and a list of the instance variables and their values (by calling inspect on each of them). User defined classes should override this method to provide a better representation of obj._ – spickermann May 09 '22 at 17:58
  • @GauravSharma It's an encoding of its memory addresses. Not that useful if you're a developer working in Ruby. However I assume it's quite useful if you're a C developer working on the Ruby-core, or developing native Ruby Gems written in C. – 3limin4t0r May 09 '22 at 18:11