[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.

There are cases where methods with self and methods with self are mixed when defining a function in a class.

Each has a name and its use and calling method are different.

table of contents

  1. Summary of each point
  2. Example for confirmation
  3. Differences in usage between class methods and instance methods
  4. Practical example (simple)

## Summary of each point The following is a summary of each relationship.
item with self No self
Method name Class method Instance method
Target Whole class Instance only
Method name example self.hello1 hello2
Example of how to call name of the class.hello1 name of the class.new.hello2

## Example for confirmation Ignore the practicality and try to define and check each function.


class TestClass
  #Method with self
  def self.hello1
    p "self hello 1"

  #Method without self
  def hello2
    p "hello 2"

In the class TestClass, there are the following two methods.

--self.hello1: Class method --hello2: Instance method

Each calling method is as follows.

Calling a class method

How to call a method with self

Call a method with self

=> "self hello 1"

=> "self hello 1"

It is OK if you execute the method directly with the class name as an object.

Instance method call

In order to call the selfless method, you need to ** create an instance and execute the method on the created instance **.

Call the self-less method

#Create and assign an instance
inst = TestClass.new

=> "hello 2"

#Create an instance and run it directly
=> "hello 2"

## Differences in usage between class methods and instance methods ** Class method is valid for all instances **, so it is often used as a method to calculate the total number of products and the number of people.

** Instance methods are valid only for that instance **, so they are often used for product generation and person generation.

### Practical example (simple) A code example that defines an instance that registers products for each product category and a class method that outputs the total number of products in all categories.

Class definition

class Product
  ######Whole class
  #Class variable (initialized with initial value 0)
  @@product_ttl_num = 0

  #Class method
  def self.ttl_num
    p "Number of products:#{@@product_ttl_num}"

  #####For each instance
  #Method to be executed automatically when instantiating
  def initialize(category)
    @product_category= category
    @product_list = []

  #Instance method (for addition)
  def add(name)
    @product_list.push name

    #Add 1 to class variable
    @@product_ttl_num += 1

That's all for class definition. Then create an instance.

Create an instance

##Instance generation (phone category)
phone = Product.new(phone)

#Instance method execution

##Instance generation(codes category)
codes = Product.new(codes)

#Instance method execution
phone.add("USB typeC")

Create two instances of phone and codes, and register a total of four products, two for each.

Execution of class method

#Class method execution

=> "Number of products: 4"

When you execute the class method, you can get the total score of the products of all instances.

Recommended Posts

[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
About the difference between classes and instances in Ruby
About the difference between "(double quotation)" and "single quotation" in Ruby
The difference between programming with Ruby classes and programming without it
Easy to understand the difference between Ruby instance method and class method.
Ruby: Differences between class methods and instance methods, class variables and instance variables
Difference between class and instance
[Ruby] I thought about the difference between each_with_index and each.with_index
Difference between instance method and class method
Difference between instance variable and class variable
[Ruby] About the difference between 2 dots and 3 dots of range object.
Think about the differences between functions and methods (in Java)
Difference between Ruby instance variable and local variable
[Ruby] Relationship between parent class and child class. The relationship between a class and an instance.
[Ruby] Difference between symbol variables and character string variables. About the difference between [: a] and ['a'].
About the difference between irb and pry
Difference between "|| =" and "instance_variable_defined?" In Ruby memoization
Find out about instance methods and self
[Rails / ActiveRecord] About the difference between create and create!
[Rails] I learned about the difference between resources and resources
What is the difference between a class and a struct? ?? ??
Calculate the difference between numbers in a Ruby array
About the relationship between HTTP methods, actions and CRUD
[Ruby] Class nesting, inheritance, and the basics of self
Difference between variables and instance variables
[Ruby] Class methods, instance methods, etc.
What is the difference between an action and an instance method?
[Java] Check the difference between orElse and orElseGet with IntStream
[Ruby] Difference between get and post
Difference between interface and abstract class
About the equals () and hashcode () methods
Understand the difference between each_with_index and each.with_index
[Ruby] Handle instance variables with instance methods
About the difference between gets and gets.chomp (other than line breaks)
[Ruby] Maybe you don't really understand? [Difference between class and module]
[Rails] Difference in behavior between delegate and has_many-through in the case of one-to-one-to-many
Note: Difference between Ruby "p" and "puts"
Difference between final and Immutable in Java
[Java] Differences between instance variables and class variables
[Firestore] Extract the collection with where condition in Ruby and delete the record
The difference between puts and print in Ruby is not just the presence or absence of line breaks
Difference between getText () and getAttribute () in Selenium
[Ruby] Difference between print, puts and p
Understand the difference between int and Integer and BigInteger in java and float and double
Difference between int and Integer in Java
[Java] Understand the difference between List and Set
[iOS] Understand the difference between frame and bounds
Difference between next () and nextLine () in Java Scanner
[Understanding] Differences between hashes and arrays in Ruby
What is the difference between SimpleDateFormat and DateTimeFormatter? ??
About next () and nextLine () of the Scanner class
[Ruby] Difference between puts and return, output and return value
Class in Ruby
About Ruby methods
[Java] Note about the difference between equivalence judgment and equality judgment when comparing String classes
[Ruby] Difference between get and post
Get the result of POST in Java
Copy and paste the source in class development ...? That's NO! Let's know about "inheritance"!
Understand in 3 minutes! A very rough explanation of the difference between session and cookie
[Swift] About the inability to distinguish between full-width and half-width characters with NS Predicate
[Java] The difference between the Stream.of () and Arrays.stream () methods that you do not know unexpectedly