2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

クラスメソッドについて調べる

Posted at

昨日は、インスタンスメソッドについて調べたので
今回はクラスメソッドについて調べる

クラスメソッドを定義する

定義する方法は、2種類ある

class クラス名
  def self.クラスメソッド名
    #処理
  end
end

定義したいクラスメソッドがたくさんある場合に
毎回selfをつけなくていいので、コードの記述量が減って便利!

class クラス名
  class << self
    def クラスメソッド名
      #処理
    end
  end
end

実際に動かす

app/models/calculation.rb
class Calculation
  def addition(a, b, c, d, e)
    puts a + b + c + d + e
  end
end

addition(1,2,3,4,5) #=> undefined method~

だと、NoMethodErrorが発生

app/models/calculation.rb
class Calculation
  def self.addition(a, b, c, d, e)
    puts a + b + c + d + e
  end
end

Calculation.addition(1,2,3,4,5) #=> 15

まとめ

・クラスメソッドとはレシーバーがクラス名でそのクラス名に対してのメソッド
・クラス全体に関わる情報を変更したり 参照したりするメソッドを作成するときに使うと便利
・定義するときは、「def self.クラスメソッド名

参考記事

チェリー本
https://qiita.com/right1121/items/c74d350bab32113d4f3d
https://qiita.com/right1121/items/c3997653a621c74fb97d

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?