Struct, , :
Person = Struct.new(:name)
Person.instance_methods(false)
p = Person.new("Bilbo")
Does `p` have an instance variable `@name` whose value is `"Bilbo"`?
p.instance_variables
, . , "":
p.members
name , Struct?
p.name
#=> "Bilbo"
p.name = "cat"
p.name
#=> "cat"
Yes! This is because instance members Structare stored in an array that you are not intended to access directly, only through accessors.
Can we add members Structdynamically? I do not know the answer to this question, but the methods do not allow to do this easily. Instead, just add instance variables and possibly accessors.
We can add an instance variable and set its value with:
p.instance_variable_set('@surname', 'Jenkins')
p.instance_variables
and get its value with:
p.instance_variable_get('@surname')
If you want to create accessors for this variable, this is one way:
p.class.instance_eval do
attr_accessor :surname
end
p.surname
p.surname = 'cat'
p.surname
p.class.instance_methods(false)
source
share