新手问题 在 module 中 require 时有个疑问想验证下

maxchen · March 19, 2018 · Last by maxchen replied at March 19, 2018 · 1040 hits

假设 app/目录下有两个文件 app/a.rb 和 app/b.rb app/a.rb文件代码如下:

module A
  Zoo = "dog"
end

如果 app/b.rb 文件代码如下:

require_relative "a"
module B
  Food = "apple"
end

我们知道 app/b.rb 文件的效果将如下所示:

module A
  Zoo = "dog"
end
module B
  Food = "apple"
end

但如果 app/b.rb 文件代码如下:

module B
  require_relative "a"
  Food = "apple"
end

那么 app/b.rb 文件的效果将是怎么样的呢?是这样

module A
  Zoo = "dog"
end
module B
  Food = "apple"
end

还是这样呢?

module B
  module A
    Zoo = "dog"
  end
  Food = "apple"
end

我自己试验了,发现 puts "#{A::Zoo}" 可以得到 dog,但是 puts "B::A::Zoo" 会出错,所以我得出的结论是:效果应该是:

module B
  module A
    Zoo = "dog"
  end
  Food = "apple"
end

不知道是否正确?跟大家确认下。

You need to Sign in before reply, if you don't have an account, please Sign up first.