ruby - 为什么人们对模块使用嵌套符号而不是::语法?

标签 ruby

在我看来,这是:

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/

相关文章:

ruby - 数组仅按日期和月份排序(忽略年份)

ruby - "database.config"在 Mongify 中的位置是什么?

ruby - 检查用户输入是否在 Ruby 中的某个范围内

ruby-on-rails - 在模型的属性名称中包含 "ID"

ruby - 在 Ruby 1.9 中不需要 RubyGems

ruby-on-rails - 如何使用 Ruby on Rails 获取硬件信息?

ruby-on-rails - Ransack:提交表单且未输入搜索值时不返回任何内容

ruby - Ruby 中的线程作用域

html - 从返回的 grape api 字符串中删除引号

ruby-on-rails - 在 Controller 中访问 helper setter