Ruby Fixnum subclass

So, I understand that you should not directly subclass Fixnum, Float, or Integer, since they do not have the #new method. Using DelegateClass seems to work, but is this the best way? Does anyone know what the reason these classes do not have #new?

I need a class that behaves like Fixnum, but has some additional methods, and I would like to be able to refer to its value via self from the class, for example:

 class Foo < Fixnum def initialize value super value end def increment self + 1 end end Foo.new(5).increment + 4 # => 10 
+7
inheritance ruby
source share
3 answers

You can easily configure the implementation of fast forwarding yourself:

 class MyNum def initialize(number) @number = number end def method_missing(name, *args, &blk) ret = @number.send(name, *args, &blk) ret.is_a?(Numeric) ? MyNum.new(ret) : ret end end 

You can then add any methods that you want to use in MyNum, but you will need to use @number in these methods, instead of directly accessing super.

+17
source share

IIRC, the main Ruby implementation, saves Fixnums as immediate values, using some of the least significant bits of a word to mark it as Fixnum instead of a pointer to an object on the heap. Therefore, on a 32-bit machine, Fixnums are only 29 bits (or whatever) instead of a complete word.

Therefore, because of this, you cannot add methods to a single "instance" of Fixnum, and you cannot subclass it.

If you are set to a โ€œFixnum-like class,โ€ you may have to create a class with a Fixnum instance variable and redirect the method calls accordingly.

+4
source share

Could you extend FixNum? How...

 class Fixnum def even? self % 2 == 0 end end 42.even? 
+2
source share

All Articles