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? *