的MatchData.new
方法正在explicitly undefined:
rb_cMatch = rb_define_class("MatchData", rb_cObject);
rb_define_alloc_func(rb_cMatch, match_alloc);
rb_undef_method(CLASS_OF(rb_cMatch), "new"); // <- here
您可以通过undef_method
做相同的纯Ruby:
class Bar
class << self
undef_method :new
end
def initialize
@bar = '123' # <- for demonstration purposes
end
end
试图调用Bar.new
现在将产生一个错误:
Bar.new #=> undefined method `new' for Bar:Class (NoMethodError)
要没有new
方法创建一个新的实例,就可以调用手动allocate
(也许initialize
,太):
bar = Bar.allocate #=> #<Bar:0x007f9eba047cd8>
Bar.send(:initialize) #=> "123"
bar #=> #<Bar:0x007fd8e0847658 @bar="123">
(send
是必要的,因为initialize
是私有的)
很多,您可以通过使类私人做的核心类由于各种原因违反了规则。有时候,他们为自己的特殊而走出困境令人非常痛心。 – tadman
@tadman违反规则? – Stefan
你知道,无法初始化的对象,它们基本上是其他进程的神奇副产品。和Fixnum一样,这不是你可以调用'Fixnum.new'的地方,因为在内部,整数实际上只是对象。 – tadman