Add the same method to multiple classes

I have code that calculates the nth root of a number. Right now, this method only works with Fixnum, because I defined it inside the Fixnum class. It would be very simple to do

class Float #same code as was in Fixnum end 

but it seems unnecessary. I have no idea how to call classes dynamically. I tried:

 classes = [Fixnum, Float] classes.each do |x| x.instance_eval do def root(pow) return self ** (1/pow.to_f) end end end 

but it didn’t work. How can I do it? Note After the publication, I realized that this may be better for Programmers.SE, since it is theoretical, as well as based on one problem. Feel free to migrate accordingly ...

+6
source share
2 answers

The corresponding part of the class hierarchy is as follows:

So copy your change to Numeric to cover them right away:

 class Numeric def root(pow) return self ** (1/pow.to_f) end end 

Then you can do the following:

 >> 11.root(2) # Fixnum => 3.3166247903554 >> 2.18.root(3) # Float => 1.296638256974172 >> Rational(23, 42).root(6) # Rational => 0.9045094132598528 >> 2**1000.root(42) # Bignum => 2.2638347236157763 
+8
source

Do you want to use #class_eval:

 classes = [Fixnum, Float] classes.each do |x| x.class_eval do def root(pow) return self ** (1/pow.to_f) end end end 

See this blog post for reference.

Alternatively, you can create a module and include it in each class:

 module MyRoot def root(pow) return self ** (1/pow.to_f) end end class Fixnum include MyRoot end class Float include MyRoot end 

I lean toward the last. This is clearer what you are doing, and also allows you to make one-time additions.

+7
source

Source: https://habr.com/ru/post/914840/


All Articles