Ben Poon Ben Poon - 2 months ago 9
Ruby Question

Nested Module namespacing? Ruby

Given the following code structure...

module Foo
module Bar
class A
end
end
class B
def initialize(stuff)
...
end
end
end


How could I call B's
.new
method from within class A ?

And, is there a way to do it dynamically, if perhaps I had a string that was the class name I wanted to access?

Answer
module Foo
  module Bar
    class A
    end
  end
  class B
    def initialize(stuff)
      puts "I like #{stuff}"
    end
  end
end

From anywhere you could invoke:

include Foo
klass = "B"
Module.const_get(klass).send(:new, "cats")
  #=> "I like cats"
Comments