Skip to content

Instantly share code, notes, and snippets.

@igaiga
Last active March 28, 2024 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igaiga/d0c8a8641572e83b6d355af0fc092272 to your computer and use it in GitHub Desktop.
Save igaiga/d0c8a8641572e83b6d355af0fc092272 to your computer and use it in GitHub Desktop.

クラスメソッドを定義するときのコードで出てくる class << self

class Foo
  class << self
    def bar
      :bar
    end
  end
end

p Foo.bar

class << self は特異クラスの定義(オープン)の文法。

覚え方として、classキーワードはいつも通りの使い方で、 << が後ろにつづくオブジェクトの特異クラスを示す文法。ここではselfはFooなので、Fooクラスの特異クラスをclassキーワードでオープンしていると考えれば良い。

参考

@okuramasafumi
Copy link

なんとなくですが、

# 継承
class Child < Parent
end

# 特異クラスオープン
class Singleton << Origin
end

で、記法としては継承と特異クラスオープンはとても似ているんですよね。そういう観点で見ると、class Singleton << Origin記法にはそれほど違和感がないように思います(記法が似ているのも、クラスに対しての関係性を設定するという機能上の類似によるものな気がします)。

ただ、実際にはクラスメソッドの定義に使われるという関係上、class Singleton << selfの書き方になる場合が多く、こうなるとなんだか不思議な見た目になってしまいます。

結局、"class クラス名 関係性指定 関係対象"の記法のうち、関係性指定が特異クラスで関係対象がself == Originだという風に認識するといいのかな、なんて思いました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment