gpt4 book ai didi

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

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

我有一个为其定义常量的类。然后我定义了一个访问该类常量的类方法。这很好用。一个例子:

#! /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

关于ruby - (在 Ruby 中)允许混合类方法访问类常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1897699/

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