LoginSignup
0
0

More than 5 years have passed since last update.

[Ruby][初心者] クラスメソッドを定義する

Posted at

クラスメソッドを定義

クラスメソッドを定義するには二つの方法がある
1、メソッドごとにクラスメソッドのする場合 
→ メソッド名の頭にselfをつけるとクラスメソッドになる

2、複数のメソッドをまとめてクラスメソッドにする場合
→ class << self .... endで囲む

class Foo
  def self.first_method
   puts 'first'
  end

  class << self
    def second_method
      puts 'second'
    end

    def third_method
      puts 'third'
    end
  end
end

呼び出す時はクラス名.メソッド名の形で呼び出す

Foo.first_method
Foo.second_method
Foo.third_method
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0