将Perl转换为Ruby - 模块与类

时间:2015-04-23 22:20:01

标签: ruby perl namespaces

Perl中的命名空间非常简单,但我似乎无法找到将这个非常简单的Perl类层次结构转换为Ruby的解决方案。

的Perl

LIB / Foo.pm

package Foo;

use Foo::Bar;

sub bar {
    return Foo::Bar->new()
}

LIB /富/ Bar.pm

package Foo::Bar

sub baz {}

main.pl

use Foo;
my $foo = Foo->new();
my $bar = $foo->bar();
$bar->baz()

红宝石

模块无法实例化,因此这段代码显然不起作用:

LIB / foo.rb

require 'foo/bar.rb'

module Foo    
  def bar
    Foo::Bar.new
  end
end

LIB /富/ bar.rb

module Foo
  class Bar
    def baz
    end
  end
end

main.rb的

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)

所以我最终得到了:

LIB / foo.rb

module Foo
  class Foo
    ...
  end
end

main.rb的

foo = Foo::Foo.new

这不是我想要的。我觉得我错过了一些非常基本的东西。 :)感谢您对此有所了解。

1 个答案:

答案 0 :(得分:3)

在Ruby中,模块和类都可用于提供命名空间分离。事实上,ClassModule的子类,您可以使用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