Translate Perl to Ruby - modules versus classes

Putting names in Perl is pretty straight forward, but I can't find a solution to translate this very simple hierarchy of Perl classes into Ruby.

Perl

Library /Foo.pm

package Foo;

use Foo::Bar;

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

Library /Foo/Bar.pm

package Foo::Bar

sub baz {}

main.pl

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

ruby

Modules cannot be created, so this code will obviously not work:

Library /foo.rb

require 'foo/bar.rb'

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

Library /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

But the attempt to declare Foo as a class instead also does not work, because there is already a module with the same name:

lib/foo.rb:3:in `<top (required)>': Foo is not a class (TypeError)

So, I get:

Library /foo.rb

module Foo
  class Foo
    ...
  end
end

main.rb

foo = Foo::Foo.new

This is just not what I want. I have a feeling that I have something very fundamental. :) Thank you for shedding light on this.

+4
source share
1 answer

Ruby . Class Module, , Module, Class

Foo , , .

.

/foo.rb

require 'foo/bar.rb'

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

/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
+3

Source: https://habr.com/ru/post/1584369/


All Articles