Home>

I want to define an instance method of a class in a module that can only be accessed from within the same module in Ruby

Applicable source code
module Sample
  class A
    def foo
      puts 'boo'
    end
    def bar
      self.foo
    end
  end
  class B
    def bar
      A.new.foo
    end
  end
end


For the above code,

A.new.bar #->'boo'
B.new.bar #->'boo'
A.new.foo #->I get an error or exception


I want to be
Is it close to the state without the access modifier in Java?

Supplement (what you really want to do) In

module,
Class A: represents a certain data structure
Class B: Create an instance of A based on external input
I want to call various methods (mainly various setters) of A from B to A.
However, we want to prevent these setters from being called from the outside (to eliminate unexpected usage), and what we really want to do.

So, in that case, you can answer that it is a classic way to write in this way in Ruby.

  • Answer # 1

      

    I want to prevent these setters from being called from outside (I want to eliminate unexpected usage)

    It isimpossibleto do strictly in Ruby. Because if you use__ send __, you can callprivate, and even a method calledinstance_variable_setis available. is.

    If you want to ignore people who intentionally callprivate(just don't inadvertently use that method), you can call the methodprivateand call it__ send __.