[Ruby] This is the solution. When should I use instance variables?

People who want to read

** I somehow understood the meaning of instance variables, but how do I use local variables, instance variables, and class variables properly? ** ** To a person like myself in the past. I think that even beginners can write it so that they can understand it by reading it.

Conclusion: Scope

** Just think about the range of variables you want to use. ** ** ** In other words, the scope (the range in which variables and methods can be called) should be considered </ font>. ** ** I will explain it below.

Types of variables that can be used in Ruby

  1. Local variables
  2. Instance variables
  3. Class variables (4. Class instance variable)
  4. Global variables

Each has a different scope.

Local variables

Do not put any @ in front of the variable name. ** Can be called only within the defined method or class. ** ** If you try to call it out of scope, you will get the error ʻundefined local variable or method 〇〇〇'for main: Object (NameError) ``.

Example 1 The variable morning can only be used inside the morning_message method

local_variable.rb


def morning_message
  morning = "Morning"
  puts "#{morning}is" 
end

morning_message # =>It's morning

puts morning # => undefined local variable or method `morning' for main:Object (NameError)

Example 2 If defined directly in the class, it can be used only inside the Morning class and outside self.message.

local_variable.rb


class Morning

  morning = "Morning"

  def self.message
    puts "#{morning}is"
  end

  self.message # => undefined local variable or method `morning' for Morning:Class (NameError)

end

Instance variables

Add @ to the head. ** You can call it anywhere in a method of the same class. ** ** It can also be defined by other than the initialize method. If you try to call it out of scope, nil will be returned.

Example 1 The @ color defined in the initialize method can also be used in the put_color method.

instance_variable.rb


class Color
  def initialize(color)
    @color = color
  end

  def put_color
    puts @color
  end
end

color1 = Color.new("Blue")
color1.put_color # =>Blue

p @color # => nil

Example 2 Define an instance variable other than the initialize method

instance_variable.rb


class Color

  def initialize(color)
    @color = color
  end

  def rank
    if @color == "Blue"
      @rank = "A"
    elsif @color == "Red"
      @rank = "B"
    end
  end

  def explain
    puts "#{@color}Rank is#{@rank}is"
  end

end

color1 = Color.new("Blue")
color2 = Color.new("Red")

color1.rank
color1.explain # =>Blue rank is A

color2.rank
color2.explain # =>Red rank is B

Class variables

Prefix with @@. ** Can be called anywhere in the class. ** ** Instance variables have different values for each instance, while class variables have common values within the class. If you try to call it out of scope, you will get the error ʻuninitialized class variable @@ 〇〇〇 in Object (NameError)`.

Example @@ monitor is common to color1 and 2

class_variable.rb


class Color

  @@monitor = "Monitor 1"
  
  def initialize(color)
    @color = color
  end

  def rank 
    if @color == "Blue"
      @rank = "A"
    elsif @color == "Red"
      @rank = "B"
    end
  end

  def explain
    puts "#{@@monitor}of#{@color}ofランクは#{@rank}is"
  end

end

color1 = Color.new("Blue")
color2 = Color.new("Red")

color1.rank
color1.explain # =>Monitor 1 has a blue rank of A

color2.rank
color2.explain # =>Monitor 1 has a red rank of B

puts @@monitor #=> uninitialized class variable @@monitor in Object (NameError)

Class instance variable

A type of instance variable, which is an instance variable owned by the class itself (= defined directly in the class). So also add @ to the head. The difference from ordinary instance variables is the definition location and scope. ** Unlike instance variables, they cannot be referenced from child classes. ** (Due to the difference between instance method and class method)

Example Class instance variables cannot be referenced by child classes

class_instance_variable.rb


class Color
  @color = "Blue"

  def self.put_color
    puts @color
  end
end

class DarkColor < Color
  def self.put_dark_color
    puts "Dark#{@color}"
  end
end

Color.put_color # =>Blue
DarkColor.put_dark_color # =>Dark ... Blue is not output

Global variables

Add $ to the head. ** You can call it anywhere in your project. ** ** Since the scope is too wide, the variable name may be unintentionally covered and the contents may be rewritten, so use it only when absolutely necessary.

Example $ brightness can be called & rewritten anywhere

global_variable.rb


$brightness = 2000

class Color

  def initialize(color)
    @color = color
  end

  def explain
    puts "That#{@color}The brightness of#{$brightness}nt"
  end

end

color1 = Color.new("Blue")
color2 = Color.new("Red")

color1.explain # =>Its blue brightness is 2000nt

$brightness = 100000

color2.explain # =>Its red brightness is 100000nt

at the end

If you have any impressions, opinions, or suggestions regarding this article, please let us know.

Reference source

https://techacademy.jp/magazine/9704 https://qiita.com/tomokichi_ruby/items/a2548176d85457f622a4 https://qiita.com/shun_takagi/items/cba48fbe8c4de81b3fac http://simanman.hatenablog.com/entry/2013/03/11/210756

Recommended Posts

[Ruby] This is the solution. When should I use instance variables?
When I try to use the AWS SDK with Ruby + Lambda, `sam local` is messed up.
Since the du command used when the capacity is full is difficult to use, I tried wrapping it with ruby
What should I use for the testing framework [Rails]
[Swift] This is the solution! Illustration of Delegate implementation
A warning is displayed when trying to use a huge integer with the special variables $ 1, $ 2, $ 3 ...
What happens to instance variables when copying an instance with ruby
I investigated the enclosing instance.
This is the first post.
Use ruby variables in javascript.
[Ruby] What is an instance?
[RSpec] When you want to use the instance variable of the controller in the test [assigns is not recommended]
[Ruby] Classes, instance variables, instances, etc ...
[Ruby] Handle instance variables with instance methods
This problem is soberly difficult ... (Ruby)
[Ruby] Display the contents of variables
I tried to make full use of the CPU core in Ruby
[Ruby] How to prevent errors when nil is included in the operation