What's the point of instance_variable_set
? Aren't these two lines the same?
instance_variable_set(@name, value)
@name = value"
In Ruby, the at-sign ( @ ) before a variable name (e.g. @variable_name ) is used to create a class instance variable.
instance_variable_get. Returns the value of the given instance variable in self , or nil if the instance variable is not set. instance_variable_set. Sets the value of the given instance variable in self to the given object.
The instance variables of an object can only be accessed by the instance methods of that object. The ruby instance variables do not need a declaration. This implies a flexible object structure. Every instance variable is dynamically appended to an object when it is first referenced.
In the case of a "simple" variable assignment for an instance variable like:
@foo = "foo"
You couldn't do
"@#{foo}" = "bar" # syntax error, unexpected '=', expecting end-of-input
But you could do something similar with instance_variable_set:
instance_variable_set("@#{foo}", "bar")
p @foo # "bar"
As per your question Aren't these two lines the same?, for that example they're similar, but isn't the use people tend to give to instance_variable_set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With