如何在ruby中访问(阴影)全局函数

我想知道如何从类中定义方法fn来访问ruby中的全局函数fn 。 我通过对函数进行别名来解决这个问题:

 def fn
结束

class级酒吧
    别名global_fn fn
     def fn
         #如何在没有别名的情况下访问全局fn
         global_fn
    结束
结束

我正在寻找c ++的::以访问全局范围的东西,但我似乎找不到任何有关它的信息。 我想我不知道具体到底是什么。

在顶层, defObject添加了一个私有方法。

我可以想到三种获得顶级function的方法:

(1)使用send来调用Object本身的私有方法(仅当方法不是mutator时才有效,因为Object将是接收者)

 Object.send(:fn) 

(2)获取顶级Method实例并将其绑定到要在其上调用它的实例:

 class Bar def fn Object.instance_method(:fn).bind(self).call end end 

(3)使用super (假设没有超级Object下面的Bar重新定义函数)

 class Bar def fn super end end 

更新:

由于解决方案(2)是最好的(在我看来),我们可以尝试通过在Object上定义一个名为super_method的实用程序方法来改进语法:

 class Object def super_method(base, meth, *args, &block) if !self.kind_of?(base) raise ArgumentError, "#{base} is not a superclass of #{self}" end base.instance_method(meth).bind(self).call(*args, &block) end end 

使用如下:

 class Bar def fn super_method Object, :fn end end 

如果super_method的第一个参数必须是Bar的有效超类, super_method调用的方法的第二个参数以及所有剩余的参数(如果有)将作为参数传递给所选方法。