Variables / scope (ruby)

I hope it will be of some help to you about variables that you will use often and their usable range. Also, since I have been studying for about two and a half months, there may be mistakes. Click here for the content of the article

-** What is a variable ** -** Why are there variables? ** ** -** Variable type ** -** Usable range (scope) **

By the way, here is the version of ruby you are learning


ruby 2.6.5

What is a variable?

Think of a variable as a "box for storing arbitrary values". For example, it is an image of putting the letters "apple" in the box (variable) labeled "apple". This is expressed as "** assigning the character" apple "to the variable apple". Also, use "=" when substituting. Be careful because the meaning is different from the arithmetic "=".

apple = "Apple"

By creating (defining) a variable in this way, you can use the value of the contents just by calling this variable.

puts apple
=>Apple

Why are there variables?

The reason for this is that writing the same code over and over is a very time-consuming task, so if you define variables in advance, you can save time and correct the value even if there is a correction. Will be. For example, if you write a program that calculates the area of a circle, the area of the circle can be calculated by "radius x radius x pi". If the pi is 3.14,

#Formula for the area of a circle with a radius of 3
3 * 3 * 3.14 

#Formula for the area of a circle with a radius of 5
5 * 5 * 3.14

It can be calculated by this formula. However, if "I want you to correct the pi to 3" at the timing when you wrote the program to some extent, you need to correct all the pi with the above description. So let's define a variable for pi.

#Define the pi with the variable pi
pi = 3.14

#Formula for the area of a circle with a radius of 3
3 * 3 * pi

#Formula for the area of a circle with a radius of 5
5 * 5 * pi

By doing the above, if the circumference ratio is corrected, if the value of the variable is corrected, other expressions will also be corrected. So, for values that are used repeatedly, let's do something like "assign to a variable".

Variable type

There are 5 types of ruby variables, and the range that can be used is different for each. Variable types are classified into one of the following by the first letter.

Variable type Description Usable range (scope)
Global variables $〇〇 Can be referenced and updated from anywhere in the script
Class variables @@〇〇 Can be referenced anywhere in the class
Instance variables @〇〇 Can be referenced anywhere in the instance
Local variables 〇〇 Can only be referenced within the defined method
Pseudo variable self, nil, etc.

These variables have the concept of scope, which defines the range in which they can be used. (Except for pseudo variables) If you are not aware of this usable range, errors will occur frequently, so be careful.

Usable range (scope)

Global variables

Global variables defined with a $ at the beginning can be used regardless of the scope. The widest scope. (So be careful when using it)


$hoge = "hoge"

def huga
  puts $hoge => "hoge"
end
  huga #=> "hoge"

Class variables

A variable that is shared throughout the class and is defined as a class variable if the variable name starts with @@, such as @@ 〇〇.

class User
    @@name = "tanaka"

    def name
      puts @@name
    end
end

user_first = User.new
user_first.name #=> "tanaka"

At first glance, it is convenient, but due to the wide range, it may be overwritten unintentionally and the value may change.


class User
    def initialize(name)
        @@name = name
    end

    def name
      puts @@name
    end
end

user_first = User.new("suzuki")
user_second = User.new("sato")
user_first.name #=> "sato"
user_secont.name #=> "sato"

Instance variables

Instance variables are variables that have a value for each instance generated from the class. The scope is within the instance. Let's write it in the same way as the class variable example above.


class User
    def initialize(name)
        @name = name
    end

    def name
      puts @name
    end
end

user_first = User.new("suzuki")
user_second = User.new("sato")
user_first.name #=> "suzuki"
user_second.name #=> "sato"

Unlike before, the value is not overwritten. Instance variables are very often used when creating apps in Ruby on Rails, so make sure you understand them. For the flow of instance processing, please refer to this article because it is easy to understand.

[Ruby] I learned about classes and instances again

Local variables

Local variables are the narrowest variables and can only be used within defined methods. As in the previous example, let's change the instance variable to a local variable.


class User
    def initialize(name)
        local_name = name
    end

    def name
      puts local_name
    end
end

user1 = User.new("suzuki")
user2 = User.new("sato")
user1.name 
user2.name 
 #The following error occurs
=> undefined local variable or method `local_name' for #<User:0x00007fd91d104f48> (NameError)

If you execute it as a local variable, the above error will occur. This is because I tried to call a variable from outside the scope, so I get the error "There is no such method". As you can see, each variable has a scope, so be careful when using it.

Pseudo variable

It is a special variable that is different from a normal variable.

** self ** The object of the current method itself ** nil ** The only instance of the NilClass? Class ** true ** The only instance of the TrueClass? Class. True representative value ** false ** FalseClass? The only instance of the class. Represents false ** \ __FILE __ ** Represents the current source file name ** \ __LINE __ ** Represents the line number in the current source file

If you try to define a variable with the same variable name as these, you will get the following error:

SyntaxError ((irb):1: Can't change the value of self)
self = hoge
^~~~

Since it is Can't change the value of self, it is an error that "the value of self cannot be changed." I understand that it is a variable that was originally defined and cannot be changed. (I'm studying here)

Finally

Variable types, scope, etc ... If you do not fully understand the basics, errors will occur frequently when creating an application. The basics are really important. I will continue to study hard and deepen my understanding.

The site that I used as a reference

[Ruby] I learned about classes and instances again [Ruby 2.7.0 Reference Manual] (https://docs.ruby-lang.org/ja/latest/doc/spec=2fvariables.html#instance) [Reverse Ruby] (https://sites.google.com/site/gyakuhikiruby/home/bian-shutosukopu) Know the types of variables! How to use variable scope in Ruby

Recommended Posts

Variables / scope (ruby)
About Ruby variables
Ruby variables and methods
Range where variables can be used with ruby [Scope]
Use ruby variables in javascript.
Scope
Ruby study notes (variables & functions)
Ruby variables and functions (methods)
[Ruby] Handle instance variables with instance methods
[Basic knowledge of Java] Scope of variables
[Ruby] Display the contents of variables
Ruby learning 4
Ruby basics
Ruby learning 5
Ruby basics
Ruby Review 2
Ruby addition
Refactoring Ruby
Item 57 Minimize the scope of local variables
Ruby learning 3
Ruby setting 2
Ruby problem ⑦
Ruby learning 2
[Ruby] Block
Refactoring Ruby
ruby calculator
Ruby learning 6
Ruby settings 1
Refactoring Ruby
About scope
Ruby basics
Ruby memo
Ruby learning 1
form_with scope
Ruby Review 1
[Ruby] Module
[Ruby] Basic knowledge of class instance variables, etc.
Read environment variables with ruby ​​file [Super beginner]
Java and Swift comparison (1) Source control / Scope / Variables
[Ruby] Assign variables in conditional expressions in if statements.
Ruby: Differences between class methods and instance methods, class variables and instance variables