我如何从Rational(或任何没有构造函数的类)inheritance?
我可以很容易地inheritance,例如, String
,例如:
class MyString 'things and stuff'
但是我如何从没有构造函数的Rational
inheritance? 例如:
def MyRat NoMethodError: undefined method `new' for MyRat:Class MyRat(10).inc # => NoMethodError: undefined method `MyRat' for main:Object MyRat.send(:initialize, 10).inc # => TypeError: already initialized class # ??? # None of it works!
我找不到初始化新课程的方法。
您可以将自己的对象定义为Rational
的代理。
class MyRat < BasicObject def initialize(value) @rational = Rational(value) end def inc @rational + 1 end def method_missing(name, *args, &block) @rational.send(name, *args, &block) end end
将使用您的类中定义的方法,否则该类将委托给有理实例。
r = MyRat.new(10) # MyRat#inc is used r.inc # => (11/1) # to_int delegates to Rational r.to_int # => 10
由于Numeric没有初始化的部分解释在此线程中可用
查看C代码,我看到new()存在于Numeric和Float中,但它被特别删除:rb_cInteger = rb_define_class(“Integer”,rb_cNumeric); rb_undef_alloc_func(rb_cInteger); rb_undef_method(CLASS_OF(rb_cInteger),“new”);
#....and for floats.. rb_undef_alloc_func(rb_cFloat); rb_undef_method(CLASS_OF(rb_cFloat), "new");
ruby源代码不包含删除new的说明。 这就是为什么我想知道这背后的原因是什么。 它似乎不是ruby解释器中的技术限制。 目前,这对我来说没有多大意义。
原因是因为
这是一个内部优化。 不必创建Fixnums,它们永远不必是GC。 这使得数学比普通对象更快(至少对于Fixnums而言)。
本文“完整数值类”中介绍了其他建议和替代方法。