Confusion with instance variables object id allocation in Ruby

穿精又带淫゛_ 提交于 2019-12-12 03:49:56

问题


I was trying to understand the instance variable initialization and declaration. Doing so I tried the below code. But in the half of my thinking path,I got something interesting as below:

class Person
attr_accessor :name,:age
    def initialize(var)
     @sex = var
    end
    def objctid
        p ":age -> #{@age.object_id}"
        p ":name -> #{@name.object_id}"
        p ":sex -> #{@sex.object_id}"
    end
end
#=> nil

ram = Person.new('M')
#=> #<Person:0x2109f48 @sex="M">

ram.objctid
#":age -> 4"
#":name -> 4"
#":sex -> 17321904"
#=> ":sex -> 17321904"

I didn't use Object#instance_variable_set till now.

How does the symbols :age and :name get the memory references,as I didn't intialize them till above?

Why does the object_id of those instance variables are same ?

ram.instance_variable_set(:@age,'14')
#=> "14"

Now in the below code @age s object_id changed as I used Object#instance_variable_set to set @age.

ram.objctid
#":age -> 17884656"
#":name -> 4"
#":sex -> 17321904"
#=> ":sex -> 17321904"

ram.instance_variable_set(:@name,'Lalu')
#=> "Lalu"

ram.objctid
#":age -> 16884288"
#":name -> 17041356"
#":sex -> 17625228"
#=> ":sex -> 17625228"

* Why such different object_id of @age and @name? *


回答1:


Instance variables are created and initialized to nil when they're first referenced. For example:

class C
    def m
        puts @unset.inspect
    end
end
C.new.m

will say nil.

You don't initialize @age or @name so they're created and initialized to nil when you first reference them inside your objctid method. Since they're both nil, they will have the same object_id since there is only one nil; adding p nil.object_id to your objctid method might be fruitful.




回答2:


How does the symbols :age and :name get the memory references ?

as you haven't assigned them any value so by default they get a nil object

Why does the object_id of those instance variables are same ?

because there is only one nil



来源:https://stackoverflow.com/questions/15453509/confusion-with-instance-variables-object-id-allocation-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!