[RUBY] Difference between variables and instance variables


1. What are variables? </ B>

2. What are instance variables? </ B>

3. When to use variables and instance variables </ b>

4. What I learned from here </ b>

  1. What is a variable?

A container for storing letters and numbers!


name = aiueo

Can be used as above!

Since it is a variable, the part after "name" (aiueo) is You can put whatever you like. Of course, the variable itself can be "defined" with any name you like.

"Definition" means

name = aiueo

The state of.

"Declaration" is equivalent to "name" alone by creating a variable with a variable name.
2. What are instance variables?

A variable that defines the attributes of the data. In other words, it is each setting that the instance method defined in the class has.

Instance variables

class A
 def B
  @name = aiueo

The above are instance variables. There is a B method in the A class When the B method is applied, "aiueo" can be used with "@name" assigned.

  1. When to use variables and instance variables

Variables </ b> can only be used outside the method. You can only use it inside the method. (However, if you define a variable in an instance method, it will be called a local variable that can only be used in an instance method.)

Instance variables </ b> can be used in different instance methods as long as they are in the same class. Also, in the MVC model, when passing data from the controller to the view, it becomes a super convenient variable that can be passed over the wall!

Local variables (variables in instance methods) have the concept of scope, so you can't jump over walls.

  1. What I learned from here

Local variables are attached in the controller, I've had a "No Method Error". Also, in the each method that receives the view, I forgot to add "@" and got "NameError".

The former got angry when a local variable went from the controller to the view if it wasn't defined in the first place. (Because it has become a local variable)

In the latter case, the each method cannot be used because it cannot be received as an array because "@" is not added (because each receives an array) = NameError (each cannot be used because the name is different). I think it is interpreted as such.

Recommended Posts