的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