当我尝试时,fixnum.new给出了未定义的方法错误。
Fixnum.new # undefined method `new' for Fixnum:Class (NoMethodError)为什么它给出了未定义的方法。固定课程的背后是什么机制。请解释一下。
如果我想要像fixnum这样的类(一个没有新方法的类),那么我应该做什么呢?
我使用下面的代码,但我感觉到了它的坏代码。
class TestClass < Fixnum
end当我试图创建新对象时,如下所示:
TestClass.new #undefined method `new' for TestClass:Class这样做对吗?或者如果你有别的办法,请在这里解释。
发布于 2014-01-31 11:53:40
如果我正确地回答了您的问题,您将尝试使用new方法编写一个不可实例化的类。您可以借鉴Singleton模块的想法,并使new (和allocate)方法成为私有的:
class Whatever
private_class_method :new, :allocate
end
Whatever.new
# NoMethodError: private method `new' called for Whatever:Class发布于 2014-01-31 11:46:52
正如我所解释的in this answer,Fixnum没有提供.new方法。这是因为您期望以以下方式创建一个新的Fixnum (或诸如Integer或Float这样的后代)
1.3
1因为,尽管它们是对象,但Fixnum没有多个实例。在同一答案中,我还解释了如何在不提供此类初始化的对象周围使用代理类。
下面是一个代码示例
class MyFixnum < BasicObject
def initialize(value)
@fixnum = value
end
def inc
@fixnum + 1
end
def method_missing(name, *args, &block)
@fixnum.send(name, *args, &block)
end
end
m = MyFixnum.new(1.3)
m.to_i
# => 1发布于 2014-01-31 11:46:48
因为每个整数值都有Fixnum对象(而且只包含)。不应创建任何其他对象。因此,从Fixnum继承可能不是一个好主意。
您可能想使用组合代替:
class TestClass
attr_reader :num # fixnum
endhttps://stackoverflow.com/questions/21479224
复制相似问题