我有一些代码来计算数字的第n个根.现在,该方法仅适用于Fixnum,因为我在Fixnum类中定义了它.这样做很容易
class Float
#same code as was in Fixnum
end
Run Code Online (Sandbox Code Playgroud)
但这似乎是不必要的.我不知道如何动态调用类.我试过了:
classes = [Fixnum, Float]
classes.each do |x|
x.instance_eval do
def root(pow)
return self ** (1/pow.to_f)
end
end
end
Run Code Online (Sandbox Code Playgroud)
但那没用.我该怎么做呢? 注意:发布后,我意识到这可能更适合Programmers.SE,因为它是理论上的,也是基于单一问题的.随意迁移...
类层次结构的相关部分如下所示:
因此,将您的更改修补为数字以立即覆盖它们:
class Numeric
def root(pow)
return self ** (1/pow.to_f)
end
end
Run Code Online (Sandbox Code Playgroud)
然后你可以做这些事情:
>> 11.root(2) # Integer
=> 3.3166247903554
>> 2.18.root(3) # Float
=> 1.296638256974172
>> Rational(23, 42).root(6) # Rational
=> 0.9045094132598528
>> 2**1000.root(42) # Integer
=> 2.2638347236157763
Run Code Online (Sandbox Code Playgroud)
你会想要使用#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
Run Code Online (Sandbox Code Playgroud)
请参阅此博客文章作为参考.
或者,您可以创建一个模块并将其包含在每个类中:
module MyRoot
def root(pow)
return self ** (1/pow.to_f)
end
end
class Fixnum
include MyRoot
end
class Float
include MyRoot
end
Run Code Online (Sandbox Code Playgroud)
我倾向于后者.你正在做的更清楚,并允许一次性添加.