在我看来,这是:
class Lifeforms::Animals::Person
# stuff goes here
end
看起来比这更具可读性:
module Lifeforms
module Animals
class Person
# stuff goes here but it's all indented
end
end
end
但是我看到的所有代码好像都是后一种方式。这有什么特别的原因吗?一个问题是模块可能没有定义......但对我来说这甚至比最后一个例子更好:
# Just make sure the modules exist
module Lifeforms
module Animals
end
end
class Lifeforms::Animals::Person
# stuff goes here
# and it doesn't all have to be deeply indented
end
为什么人们会采取中间方式?是不是只有我一个人认为深度嵌套会使代码更难阅读?
最佳答案
我同意,我有时会使用::语法。但是请注意,这两种语法的常量解析语义不同,因此它们并不完全等同:
module A; module B; module C; end ;end ;end
module A; A_CONST=42; end
module A::B::C; puts A_CONST; end
#^ NameError: uninitialized constant A::B::C::A_CONST
module A
module B
module C
puts A_CONST
end
end
end
#^ prints 42
关于ruby - 为什么人们对模块使用嵌套符号而不是::语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29300208/