How can I inherit Rational (or any class without a constructor)?

I can easily inherit, for example, String , for example:

 class MyString < String def stuff self + ' and stuff' end end # This works: MyString.new('things').stuff # => 'things and stuff' 

But how can I inherit from Rational , which does not have a constructor? For instance:

 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! 

I cannot find a way to initialize my new class.

+6
source share
1 answer

You can define your own object as a proxy server around 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 

The methods defined in your class are used, otherwise the class will delegate to a rational instance.

 r = MyRat.new(10) # MyRat#inc is used r.inc # => (11/1) # to_int delegates to Rational r.to_int # => 10 

A partial explanation that Numeric does not have initialization is available in this thread.

Looking at the C code, I see that new () exists in Numeric and Float, but it is specially removed: 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"); 

The source code for ruby ​​does not explain how to remove the new one. That’s why I’m wondering what the arguments are. It does not appear to be a technical limitation in the ruby ​​interpreter. Currently, it does not really matter to me.

and the reason is because

This is an internal optimization. Fixnums do not need to be created and they should never be GC'ed. This makes mathematics much easier than it would be with ordinary objects (at least for Fixnums).

Additional suggestions and alternatives are explained in this article Full Number Class .

+5
source

All Articles