tackleberry
tackleberry

Reputation: 1013

Why Ruby Instance Variables object_id s are weird

Below is the test case, I was just trying to do something with dup method. But I realized this weird behavior. I couldn't find any reasonable explanation.

class ObjectIdTest
  attr_accessor :x, :y
  def initialize
    @x, @y = 1, 2
  end

  def object_ids
    "x:#{@x.object_id}, y: #{@y.object_id}"
  end
end

class ObjectIdTestChild < ObjectIdTest
  attr_accessor :z
  def initialize
    @z = 3
  end

  def object_ids
    super + " z: #{@z.object_id}"
  end
end

oid1 = ObjectIdTest.new
oid2 = ObjectIdTestChild.new
p oid2.object_ids

oid3 = oid2.dup
p oid3.object_ids

Output: "x:4, y: 4 z: 7"

"x:4, y: 4 z: 7"

  1. Normally object ids' are longer (like 70322728590900), why these are so smaller? (Are they relative or something like that?)
  2. Why x's and y's object id are the same?
  3. Why oid2 and oid3 's instance variables have the same object id?

Upvotes: 0

Views: 156

Answers (1)

fmendez
fmendez

Reputation: 7338

1 - Objects other than Fixnumber have bigger values. For instance:

 "hello".object_id #=> 70256148388440
 0x3FFFFFFFF.object_id #=> 34359738367

2 and 3 - Althought dup produces a shallow copy of an object, in this case that object happens to represent the same Fixnums. With Fixnums the same number has always the same object_id. Ruby Object

Upvotes: 1

Related Questions