当我尝试使用fixnum.new时,会给出未定义的方法错误。
Fixnum.new # undefined method `new' for Fixnum:Class (NoMethodError)
为什么它给出未定义的方法。 fixnum类背后有什么机制。请解释一下。
如果我想创建像fixnum这样的类(没有新方法的类)那么我该怎么做?
我会使用下面的代码,但我感觉它的代码很糟糕。
class TestClass < Fixnum
end
当我尝试创建如下所示的新对象时:
TestClass.new #undefined method `new' for TestClass:Class
这是正确的方法吗?或者如果您有其他方式,请在此解释。
答案 0 :(得分:2)
正如我解释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
答案 1 :(得分:1)
如果我的问题是正确的,那么您正在尝试编写一个使用new
方法无法实例化的类。您可以从Singleton
模块借用这个想法,并将new
(和allocate
)方法设为私有:
class Whatever
private_class_method :new, :allocate
end
Whatever.new
# NoMethodError: private method `new' called for Whatever:Class
答案 2 :(得分:0)
因为每个(和仅)整数值都有Fixnum
个对象。不应该创建其他对象。因此,继承Fixnum
可能不是一个好主意。
您可能希望改为使用合成:
class TestClass
attr_reader :num # fixnum
end