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

【Ruby】class << selfとは

Posted at

##class << selfとは
特異クラス定義式のこと。
クラスメソッドはクラスインスタンスに属する特異メソッドですが、上記の形式でのクラスメソッドの定義は「<<」の後ろにクラスインスタンスを指定し、その「クラスインスタンスの特異クラスを定義している」とみることができる。
https://www.school.ctc-g.co.jp/columns/nakagoshi/nakagoshi12.html

クラスメソッドを定義するときに全てのクラスメソッドにself.をつけるのが手間なときに特異クラスを使うと便利。

foo.rb
class Foo < ApplicationRecord
  class << self
    def bar
      puts 'bar'
    end
  end
end
foo.rb
class Foo < ApplicationRecord
  def self.bar
    puts 'bar'
  end
end

上2つのコードは同じ意味になる。

##参考

より詳しい特異クラスと特異メソッドの説明は下記参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?