我可以轻松地继承,String
例如,像这样:
class MyString < String
def stuff
self + ' and stuff'
end
end
# This works:
MyString.new('things').stuff # => 'things and stuff'
但是,如何从Rational
没有构造函数的继承?例如:
def MyRat < Rational
def inc
self + 1
end
end
# I have tried to initialize like this:
MyRat.new(10).inc # => 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源代码中没有删除新内容的说明。这就是为什么我想知道这背后的原因是什么。在ruby解释器中,这似乎不是技术限制。目前,这对我来说意义不大。
原因是因为
这是内部优化。Fixnums不必创建,也不必进行GC处理。与普通对象相比,这使数学运算速度大大提高(至少对于Fixnums而言)。
本文“完整数值类”中介绍了其他建议和替代方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句