LoginSignup
2
0

More than 5 years have passed since last update.

シングルトンクラスのインスタンスは作れない

Posted at

Rubyならできると思ったんだけど。

class Sample; end

class << Sample
  def initialize; end
end

# Sample.singleton_class.new でも同じ
(class << Sample; self; end).new

# これでももちろんだめ
Sample.singleton_class.class_eval do |obj|
  obj.new
end

can't create instance of singleton class (TypeError) でエラー。頑張ったら相応のことはいけそうな気がするけど。

Note) ちなみにシングルトンクラスのサブクラスも作れない。仮に、サブクラスを作れるとしたら、そのクラスがシングルトンクラスかどうか見分けがつかず、インスタンスを作成することができてしまい、矛盾を発生してしまうからかも。

class Sample; end
Class.new(Sample.singleton_class) # can't make subclass of singleton class (TypeError)
2
0
3

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