Perl中的命名空间非常简单,但我似乎无法找到将这个非常简单的Perl类层次结构转换为Ruby的解决方案。
package Foo;
use Foo::Bar;
sub bar {
return Foo::Bar->new()
}
package Foo::Bar
sub baz {}
use Foo;
my $foo = Foo->new();
my $bar = $foo->bar();
$bar->baz()
模块无法实例化,因此这段代码显然不起作用:
require 'foo/bar.rb'
module Foo
def bar
Foo::Bar.new
end
end
module Foo
class Bar
def baz
end
end
end
require 'lib/foo.rb'
foo = Foo.new
bar = foo.bar
bar.baz
但是尝试将Foo声明为一个类也不起作用,因为已经有一个名称的模块:
lib/foo.rb:3:in `<top (required)>': Foo is not a class (TypeError)
所以我最终得到了:
module Foo
class Foo
...
end
end
foo = Foo::Foo.new
这不是我想要的。我觉得我错过了一些非常基本的东西。 :)感谢您对此有所了解。
答案 0 :(得分:3)
在Ruby中,模块和类都可用于提供命名空间分离。事实上,Class
是Module
的子类,您可以使用Module
做的大多数事情也可以使用Class
如果Foo
需要成为一个班级,请将其声明为班级,不要将其声明为模块。
E.g。
<强> LIB / foo.rb 强>
require 'foo/bar.rb'
class Foo
def bar
Foo::Bar.new
end
end
<强> LIB /富/ bar.rb 强>
class Foo
class Bar
def baz
end
end
end
<强> main.rb的强>
require 'lib/foo.rb'
foo = Foo.new
bar = foo.bar
bar.baz