Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `instance_variable_set` necessary in Ruby?

Tags:

ruby

What's the point of instance_variable_set? Aren't these two lines the same?

instance_variable_set(@name, value)
@name = value"
like image 487
Fei Qu Avatar asked Oct 28 '18 02:10

Fei Qu


People also ask

What does @variable mean in Ruby?

In Ruby, the at-sign ( @ ) before a variable name (e.g. @variable_name ) is used to create a class instance variable.

What is Instance_variable_get in Ruby?

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.

How do you access instance variables in Ruby?

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.


1 Answers

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.

like image 160
Sebastian Palma Avatar answered Oct 22 '22 16:10

Sebastian Palma