将 Perl 翻译成 Ruby - 模块与 类

Translating Perl to Ruby - modules vs. classes

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

Perl

lib/Foo.pm

package Foo;

use Foo::Bar;

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

lib/Foo/Bar.pm

package Foo::Bar

sub baz {}

main.pl

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

Ruby

模块无法实例化,所以这段代码显然行不通:

lib/foo.rb

require 'foo/bar.rb'

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

lib/foo/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 声明为 class 也不起作用,因为已经有一个同名的模块:

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

这不是我想要的。我觉得我错过了一些非常基本的东西。 :) 感谢您阐明这一点。

在Ruby中,模块和classes都可以用来提供命名空间分离。事实上 ClassModule 的一个子 class,大多数你可以用 Module 做的事情你也可以用 Class[=18= 做]

如果 Foo 需要是 class,请将其声明为 class,不要将其声明为模块。

例如

lib/foo.rb

require 'foo/bar.rb'

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

lib/foo/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