Ruby: Differences between class methods and instance methods, class variables and instance variables

Difference between class method and instance method

First, let's look at the difference between Ruby class methods and instance methods.

What is a class method?

It can be used by the class itself that defines the class method. It is used for processing that uses common information in the class. You can call it without an instance.

When defining a class method, write self. method name. It can be called from the class name Fruits as follows. Also, the new method that creates an instance is a typical class method.

fruits.ruby


calss Fruits
  def self.call #self refers to the class itself
    puts "Called a class method"
  end
end

Fruits.new #The new method is also one of the class methods.
Fruits.call

Running the above ruby ​​file in a terminal gives the following result:

Terminal


ruby fruits.rb

Called a class method

The execution result of Fruits.call is displayed. Fruits.new will not be displayed in the execution result as it will only generate an empty instance.

What is an instance method?

A method that can be used by the instance and is defined in the class. You can use the instance generated from "Class that defines the instance method".

fruits.ruby


calss Fruits
  def call
     puts "I called an instance method"
  end
end

fruits = Fruits.new
fruits.call
#.You can also connect them with and call them as follows.
Fruits.new.call

Terminal


ruby fruits.rb

I called an instance method

initialize method

The initialize method is an instance method that can define the process that is executed at the same time that the instance is created by the new method. Actually, the initialize method is executed automatically even if you do not write it in the class, and in this case nothing is processed.

fruits.rb


class Fruits
  def initialize
    puts "Instance was created"
  end
end

Fruits.new

Running the above ruby ​​file in a terminal gives the following result:

Terminal


ruby fruits.rb

Instance was created

You can see that the process defined in the initialize method was executed after the instance was created in Fruits.new.

Differences between class variables and instance variables

Next, let's look at the difference between class variables and instance variables.

What is a class variable?

It is a variable defined in the class and is defined by writing @@ variable name. Class variables are suitable for use when you want to define common variables as a class.

fruits.rb


class Fruits

  @@fruit = "Orange" #Defined before instantiation for use within the initialize method

  def initialize
    puts "I#{@@fruit}I like"
  end

end

Fruits.new

Execution result

Terminal


ruby fruits.rb

I like oranges

A feature of class methods is that once defined, they can be used anywhere in the class.

fruits.rb


class Fruits

  @@price = 0 

  def initialize(fruit, price)
    @fruit = fruit
    @@price += price
  end

  def self.sum
    puts "The total amount is#{@@price}It's a yen" 
  end

end

Fruits.new("Orange", 200)
Fruits.new("Apple", 300)
Fruits.new("Grape", 500)

Fruits.sum

Terminal


ruby fruits.rb

The total amount is 1000 yen

The price of each fruit was added to the class variable @@ price each time an instance of orange, apple, or grape was created, and the total amount was output by thesummethod.

What is an instance variable?

A variable that can be defined in an individual instance, and is defined by writing @variable name. Instance variables can be used in instance methods other than the defined instance methods.

fruits.rb


class Fruits

  def initialize(fruit)
    @fruit = fruit
    puts "I#{@fruit}I like"
  end

  def dislike
    puts "I#{@fruit}I'm not good at"
  end
end

Fruits.new("Orange")
Fruits.new("Apple")
fruit = Fruits.new("Grape")
fruit.dislike

Terminal


ruby fruits.rb

I like oranges
I like apples
I like grapes
I'm not good at grapes

In the initialize method, the value of the instance variable @ fruit is assigned to each created instance and output by puts.

You can also see that the instance variable @ fruit defined in the initialize method can also be used in the dislike method.

Reference material

Active engineers explain how to use Ruby class variables [For beginners](TechAcademy Magazine)

Recommended Posts

Ruby: Differences between class methods and instance methods, class variables and instance variables
[Java] Differences between instance variables and class variables
Ruby variables and methods
Difference between class and instance
[Ruby] Class methods, instance methods, etc.
Ruby variables and functions (methods)
Difference between instance method and class method
Difference between instance variable and class variable
[Ruby] Handle instance variables with instance methods
Differences between Applet class and JApplet class
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
Difference between Ruby instance variable and local variable
Differences between Ruby strings and symbols [Beginner]
Easy to understand the difference between Ruby instance method and class method.
[Ruby] Basic knowledge of class instance variables, etc.
[Understanding] Differences between hashes and arrays in Ruby
About Ruby instance methods
[Ruby] methods, instance methods, etc ...
[Ruby] Difference between receiver and object. Differences between Ruby objects and JS objects
Differences between Ruby syntax error statements in Ruby and binary
Differences between browser sessions and cookies and Rails session and cookies methods
[Java Silver] What are class variables instance variables and local variables?
[Self-use memo] (Ruby) class, class instance, instance
Relationship between package and class
What are Ruby class methods?
About Java class variables class methods
Differences between IndexOutOfBoundsException and ArrayIndexOutOfBoundsException
[Ruby] Singular methods and singular classes
Ruby methods and classes (basic)
About instance variables and attr_ *
[Ruby] Singular methods and singular classes
[Rails] Differences between redirect_to and render methods and how to output render methods
Think about the differences between functions and methods (in Java)
[Ruby] Difference between get and post
Difference between interface and abstract class
Differences between "beginner" Java and Kotlin
[Ruby] Difference between is_a? And instance_of?
Ruby standard input and various methods
[Ruby] Classes, instance variables, instances, etc ...
Organize classes, instances, and instance variables
Differences between find, find_by, find_by_sql methods
Differences between Java and .NET Framework
[Ruby] Maybe you don't really understand? [Difference between class and module]
[Ruby] Difference between symbol variables and character string variables. About the difference between [: a] and ['a'].
[Java] Introductory structure Class definition Relationship between class and instance Method definition format
Differences between preface and postfix of operators
Java programming (static clauses and "class variables")
Difference between "|| =" and "instance_variable_defined?" In Ruby memoization
[Ruby] Difference between print, puts and p
Find out about instance methods and self
[Ruby] How to calculate the total amount using the initialize method and class variables
Instance concept, class type variables, constructors, static members
Summarize the differences between C # and Java writing
[Ruby] Difference between puts and return, output and return value
Ruby How to convert between uppercase and lowercase
Class and model
Functions and methods
Variables / scope (ruby)
String class methods
About Ruby variables
Ruby and Gem