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

(在Ruby中)允许混合类方法访问类常量

发布时间:2020-12-16 19:47:18 所属栏目:百科 来源:网络整理
导读:我有一个定义为常量的类.然后我有一个类方法定义,访问该类常量.这工作正常一个例子: #! /usr/bin/env rubyclass NonInstantiableClass Const = "hello,world!" class self def shout_my_constant puts Const.upcase end end endNonInstantiableClass.shout_
我有一个定义为常量的类.然后我有一个类方法定义,访问该类常量.这工作正常一个例子:
#! /usr/bin/env ruby

class NonInstantiableClass
    Const = "hello,world!"
    class << self
        def shout_my_constant
            puts Const.upcase
            end
        end
    end

NonInstantiableClass.shout_my_constant

我的问题出现在尝试将此类方法移至外部模块,如下所示:

#! /usr/bin/env ruby

module CommonMethods
    def shout_my_constant
        puts Const.upcase
        end
    end

class NonInstantiableClass
    Const = "hello,world!"
    class << self
        include CommonMethods
        end
    end

NonInstantiableClass.shout_my_constant

Ruby将该方法解释为从模块请求一个常量,而不是类:

line 5:in `shout_my_constant': uninitialized constant CommonMethods::Const (NameError)

那么,你们的什么魔术技巧必须让方法访问类常数?非常感谢.

解决方法

这似乎工作:
#! /usr/bin/env ruby

module CommonMethods
    def shout_my_constant
        puts self::Const.upcase
    end
end

class NonInstantiableClass
    Const = "hello,world!"
    class << self
        include CommonMethods
    end
end

NonInstantiableClass.shout_my_constant

HTH

(编辑:李大同)

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

    推荐文章
      热点阅读