Using “::” instead of “module …” for Ruby namespacing

百般思念 提交于 2019-12-30 08:14:30

问题


In Ruby, is there a difference between writing class Foo::Bar and module Foo; class Bar for namespacing? If so, what?


回答1:


If you use class Foo::Bar, but the Foo module hasn't been defined yet, an exception will be raised, whereas the module Foo; class Bar method will define Foo if it hasn't been defined yet.

Also, with the block format, you could define multiple classes within:

module Foo
  class Bar; end
  class Baz; end
end



回答2:


Also notice this curious bit of Ruby-ismness:

FOO = 123

module Foo
  FOO = 555
end

module Foo
  class Bar
    def baz
      puts FOO
    end
  end
end

class Foo::Bar
  def glorf
    puts FOO
  end
end

puts Foo::Bar.new.baz    # -> 555
puts Foo::Bar.new.glorf  # -> 123


来源:https://stackoverflow.com/questions/6927566/using-instead-of-module-for-ruby-namespacing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!