开发者

Using "::" instead of "module ..." for Ruby namespacing

In Ruby, is there a difference between writing class Foo::开发者_开发技巧Bar and module Foo; class Bar for namespacing? If so, what?


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜