Jeremy Rajan Jeremy Rajan - 4 months ago 14
Ruby Question

Private common methods in Ruby Modules

Apologies, for being a bit noob'ish! :). Is there a way that I can have common private methods to be inside the classes that I have defined in it. For ex, can I have:

Module MyMod
class MyClass
...
method1()
end
class MyClass2
...
method1()
end
private
def method1()
...
end
end


I am guessing, calling them as follows:

a = MyMod::MyClass.new


But it gives me an error, that method1 is not available.

Something along these lines? I tried using self class but doesn't seem to work.

Thank you!

Answer

Please try this way

module MyModule
  class A
    def my_method_a
      MyModule.my_method
    end
  end

  class B
    def my_method_b
      MyModule.my_method
    end
  end

  private
  module_function
  def my_method
    puts "hello"
  end
end

and then

a = MyModule::A.new 
a.my_method_a