2012-05-03 53 views
6

我有一些代码可以计算数字的第n个根。现在,该方法仅适用于Fixnum,因为我在Fixnum类中定义了它。这将是非常容易的只是做将相同的方法添加到多个类

class Float 
    #same code as was in Fixnum 
end 

但这似乎是不必要的。我不知道如何动态调用类。我试过了:

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

但是没有奏效。我该怎么做呢? 注意:发布后,我意识到这可能更适合Programmers.SE,因为它是理论上的,以及基于单一问题的。随意相应迁移...

+2

注在上面的'返回'是没有必要的(是非惯用语)。 – Phrogz

回答

8

的类层次结构的相关部分看起来是这样的:

所以修补改变成数字同时涵盖所有这些:

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

然后你就可以做这些事情:

>> 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 
7

你要使用#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 

this blog post作为参考。

或者,你可以创建一个模块并将其包含到每个类:

module MyRoot 
    def root(pow) 
    return self ** (1/pow.to_f) 
    end 
end 

class Fixnum 
    include MyRoot 
end 

class Float 
    include MyRoot 
end 

我向后者倾斜。它更清楚你在做什么,并允许一次性添加。

+0

+1表示正常,但-1表示没有针对实际需要的正确答案:从“Numeric”继承。 – Phrogz

相关问题