protectedとprivate
protected:定義されているクラスのインスタンスであれば呼び出せる
private:そのオブジェクト(selfを使う文脈)からしか呼び出せない
どちらも:定義されているクラスとサブクラスのインスタンスメソッド内でのみ呼び出せる。
class Piyo def internal protected_method private_method end def receiver_self self.protected_method self.private_method end def receiver_other(other) other.protected_method # OK other.private_method # Error end protected def protected_method puts 'protected' end private def private_method puts 'private' end end class PiyoSub < Piyo def from_child protected_method private_method end def from_child_receiver(other) other.protected_method other.private_method end end p1 = Piyo.new p2 = Piyo.new sub = PiyoSub.new # 外からは呼び出せない p1.protected_methods # Error p1.private_methods # Error # 定義されているクラスのインスタンスメソッドから呼び出せる # privateは他のインスタンスからは呼び出せない p1.internal # OK p1.receiver_self # OK p1.receiver_other(p2) # protectedのみOK # サブクラスのインスタンスメソッドから呼び出せる 挙動は親クラスと同じ sub.from_child # OK sub.from_child_receiver(p1) # protectedのみOK