[Ruby] What are Ruby class methods?

1 minute read

Introduction

One of the items that stumbled upon in Ruby, a class method. I will write what I didn’t understand.

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

What is # method

What is the method as a prerequisite? A method is an “action” that data has.

When you think about it in a car, The behavior that the data of a car has is “run, stop, give a winker”.

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 .self is prepended to the method name.

test.rb


class Car
  def self.run # Define class method by adding self before method name
    puts "runs"
  end
end

Car.run #classname.methodname will run the defined class method

(Added June 29, 2020. Thank you for pointing out: bow_tone1:) Alternatively, you can write a method between class « self and end. The nesting is one step deeper, but if you want to define a lot of class methods, you don’t have to add .self before the method name.

test.rb


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

Finally

The points to note for class methods are:

・When defining, add .self in front of the method name. ・Or, 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.