我想知道如何fn从类中定义一个方法来访问ruby中的全局函数fn.我通过别名函数做了一个解决方法,如下所示:
def fn
end
class Bar
alias global_fn fn
def fn
# how to access the global fn here without the alias
global_fn
end
end
我正在寻找c ++的::以访问全局范围的东西,但我似乎找不到任何有关它的信息.我想我不知道具体到底是什么.
hor*_*guy 17
在顶层,def添加一个私有方法Object.
我可以想到三种方法来获得顶级功能:
(1)send用于调用私有方法Object(仅当方法不是mutator时才有效,因为Object它将是接收者)
Object.send(:fn)
Run Code Online (Sandbox Code Playgroud)
(2)获取Method顶级方法的实例并将其绑定到要在其上调用它的实例:
class Bar
def fn
Object.instance_method(:fn).bind(self).call
end
end
Run Code Online (Sandbox Code Playgroud)
(3)使用super(假设Bar下面没有超类Object重新定义函数)
class Bar
def fn
super
end
end
Run Code Online (Sandbox Code Playgroud)
更新:
由于解决方案(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
Run Code Online (Sandbox Code Playgroud)
使用如下:
class Bar
def fn
super_method Object, :fn
end
end
Run Code Online (Sandbox Code Playgroud)
如果第一个参数super_method必须是有效的超类Bar,则第二个参数是要调用的方法,所有剩余的参数(如果有的话)作为参数传递给选定的方法.