gpt4 book ai didi

ruby - 在 ruby​​ 模块中分配常量

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

我有一个模块:

module Foo
module Bar
TEST = "ok"

def self.is_ok; true end
end
end

Foo::Bar::TEST # => "ok"
Foo::Bar.is_ok # => true

我想在定义的模块中有另一个常量,只有一次。

我试过这样的:

module Foo
module Bar
TEST = is_ok

def self.is_ok; true end
end
end

然后我收到一条错误消息,提示 undefined local variable or method 'is_ok' for Foo::Bar:Module。这意味着 is_ok 尚未定义。

常量是否在模块类方法以外的某个时间点定义?

另外,我还有一个例子:

module Foo
module Bar
TEST = "ok"

def self.is_ok; true end
end

module YYY
TEST = Foo::Bar::TEST
TEST2 = Foo::Bar.is_ok
end
end

在这里,我得到:

Foo::Bar::TEST2 # => true

正如预期的那样。

最佳答案

这只是定义顺序的问题:

module Foo
module Bar
def self.is_ok
true
end
TEST = is_ok
end
end

完全按照您的预期工作。

原因很简单,Ruby 类定义是逐行求值的;在您的示例中分配 TEST 时,::is_ok 尚未定义!

关于ruby - 在 ruby​​ 模块中分配常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54333320/

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