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

我有一个定义为常量的类.然后我有一个方法定义,访问该类常量.这工作正常一个例子:
#! /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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...