使用" ::"而不是“模块..."用于Ruby名称空间 [英] Using "::" instead of "module ..." for Ruby namespacing

查看:38
本文介绍了使用" ::"而不是“模块..."用于Ruby名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,为命名空间写class Foo::Barmodule Foo; class Bar之间有区别吗?如果是这样,怎么办?

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

推荐答案

如果使用class Foo::Bar,但尚未定义Foo模块,则会引发异常,而module Foo; class Bar方法将定义Foo(如果尚未定义的话).

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

这篇关于使用" ::"而不是“模块..."用于Ruby名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆