gpt4 book ai didi

ruby - 如何访问 ruby​​ 中的(阴影)全局函数

转载 作者:数据小太阳 更新时间:2023-10-29 06:36:52 24 4
gpt4 key购买 nike

我想知道如何从一个定义了方法 fn 的类访问 ruby​​ 中的全局函数 fn。我通过像这样给函数起别名来解决这个问题:

def fnendclass Bar    alias global_fn fn    def fn        # how to access the global fn here without the alias        global_fn    endend

我正在寻找与 c++ 的::类似的东西来访问全局范围,但我似乎无法找到有关它的任何信息。我想我并不清楚自己在寻找什么。

最佳答案

在顶层,def 将私有(private)方法添加到 Object

我能想到的三种获取顶层函数的方法:

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

Object.send(:fn)

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

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

(3) 使用super(假设ObjectBar的父类(super class)没有重定义函数)

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 class),第二个参数是您要调用的方法,所有剩余参数(如果有)是作为参数传递给所选方法。

关于ruby - 如何访问 ruby​​ 中的(阴影)全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2681895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com