加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:16:39 所属栏目:百科 来源:网络整理
导读:我想知道如何从一个类定义一个方法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 我正在寻找一些符
我想知道如何从一个类定义一个方法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’s ::的方式来访问全球范围,但我似乎找不到任何有关它的信息.我想我不知道我在找什么.

解决方法

在顶层,def为Object添加了一个私有方法.

我可以想到三种方式来获得顶级功能:

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

Object.send(:fn)

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

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

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

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的有效超类,您要调用的方法的第二个参数以及所有剩余的参数(如果有的话)作为参数传递给所选方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读