2017-09-06 86 views
1

为什么我们不能在Ruby中初始化TrueClass?我得到这个:为什么我们不能在Ruby中初始化TrueClass

TrueClass.new # => NoMethodError: undefined method `new' for TrueClass:Class 

但,TrueClasssuperclassObject

同样,我们无法初始化NilClassFalseClass

我只是想知道这样是可能的,即使是子类的Object。如果我们想写一个类似这样的课程,我们如何实现它?

+0

你想要达到什么目的? –

+0

只是我很想知道它是如何禁止创建新的对象? – Sanjith

+0

您是否阅读过文档? https://ruby-doc.org/core-2.2.0/TrueClass.html –

回答

7

我只是想知道这样是可能的,即使是在对象的子类。如果我们想写一个类似这样的课程,我们如何实现它?

您可以使用关键字undef取消定义继承的方法。由于new是一种类方法,因此您必须在类的单例类中使用undef。这看起来像这样:

class <<MyClass 
    undef new 
end 
MyClass.new # NoMethodError: undefined method `new' for MyClass:Class 
5

我只是想知道即使这是Object的子类也是如此。

它通过undefining allocatenew工作。这里的corresponding C code

rb_undef_alloc_func(rb_cTrueClass); 
rb_undef_method(CLASS_OF(rb_cTrueClass), "new"); 

您可以通过undef_method在Ruby中实现类似的结果:

class FooClass 
    ::FOO = new # <- this will be the only Foo instance 
    class << self 
    undef_method :allocate 
    undef_method :new 
    end 
end 

FooClass.new  #=> NoMethodError: undefined method `new' for FooClass:Class 
FooClass.allocate #=> NoMethodError: undefined method `allocate' for FooClass:Class 

FOO #=> #<FooClass:0x007fddc284c478> 

“相似”,因为TrueClass.allocate实际上并没有提出一个NoMethodError,但TypeError

TrueClass.allocate #=> TypeError: allocator undefined for TrueClass 

不幸的是,rb_undef_alloc_func在Ruby中不可用。我们可以通过重写allocate模仿行为:

class FooClass 
    class << self 
    def allocate 
     raise TypeError, "allocator undefined for #{self}" 
    end 
    undef_method :new 
    end 
end 

FooClass.allocate #=> TypeError: allocator undefined for FooClass 

不知道,哪种方式更干净。


上述变化阻止你通过new创建一个实例,但也有其他的方法:

FOO  #=> #<FooClass:0x007fddc284c478> 

FOO.dup #=> #<FooClass:0x007fad721122c8> 
FOO.clone #=> #<FooClass:0x007f83bc157ba0> 

Marshal.load(Marshal.dump(FOO)) #=> #<FooClass:0x007f83bc13e330> 

为了考虑所有这些特殊情况,红宝石” STDLIB提供Singleton模块:

require 'singleton' 

class Foo 
    include Singleton 
end 

它通过使allocatenew私有方法:(间​​)

Foo.new  #=> NoMethodError: private method `new' called for Foo:Class 
Foo.allocate #=> NoMethodError: private method `new' called for 

,并将其添加instance返回一个实例:(或情况下,只有一个)

Foo.instance #=> #<Foo:0x007fdca11117e8> 
+0

谢谢@stefan。我明白一点。所以,我的第二个问题出现了:我们可以写一个类似于这样的类吗? – Sanjith

相关问题