What are Ruby class methods?

Introduction

One of the items I stumbled upon in Ruby, the class method. I will write what I did not understand.

Click here for classes and instances [link-1]. [link-1]:https://qiita.com/fishmans0120/items/569cd9ab37b89c0c1726

What is a method

As a prerequisite, what is a method? A method is the "behavior" of the data.

If you think about it by applying it to a car, The actions that the data of a car has are "run, stop, turn signal" and so on.

What is a class method?

A method that can be used by the class itself that defines the class method. It can be used for processing that has common information in the class. The definition method is the same as other methods, but prefix the method name with .self.

test.rb


class Car
  def self.run #Define a class method by prefixing the method name with self
    puts "run"
  end
end

Car.run #name of the class.You can execute the defined class method by the method name

(Added on June 29, 2020. Thank you for pointing out: bow_tone1:) Alternatively, you can write a method between class << self and end. Nesting is one step deeper, but if you want to define a lot of class methods, you don't have to prefix the method name with .self every time.

test.rb


class Car
  class << self
    def run
      puts "run"
    end
  end
end

Finally

The notes of the class method are as follows.

-When defining, add .self before the method name. -Alternatively, there is a notation to write a method between class << self and end. -This method can be used only for classes.

Thank you for reading to the end.

Recommended Posts

What are Ruby class methods?
[Ruby] Class methods, instance methods, etc.
About Ruby methods
[Ruby] methods, instance methods, etc ...
[Java Silver] What are class variables instance variables and local variables?
[Java] What is class inheritance?
About Java class variables class methods
Ruby methods and classes (basic)
[Java basics] What is Class?
What are Java metrics? _Memo_20200818
What are the rules in JUnit?
What is a Ruby 2D array?
Ruby methods often used in Rails
[Java] What are overrides and overloads?
[Ruby] Class nesting, inheritance, and the basics of self
Handling of date and time in Ruby. Use Date and Time properly.
What are Ruby class methods?
[Ruby] Class methods, instance methods, etc.
[Java basics] What is Class?