问题
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