他の言語とかでも可視性の話はあるけれど、Rubyでの特徴は下記ということらしい。
public
の場合は当該インスタンスのものは、どこからでも呼び出しできる。public
以外のものは、クラス内もしくはサブクラス内からしか呼出できない。
protected
とprivate
の違いは、同じクラスもしくはサブクラスのインスタンス間の可視性の部分かなと思った。
protected
は、同じクラスもしくはサブクラスなら呼び出しできて、private
は名前の通り自インスタンスからのみ呼び出せる。
上記の内容のイメージは下記のような感じだと思った😅
項目 | クラス外参照 | 同一クラスのインスタンス間参照 |
---|---|---|
public | ⭕️ | ⭕️ |
protected | ❌ | ⭕️ |
private | ❌ | ❌ |
実際に色々試してみたのが下記。理解したような結果になっているので、多分正しいはず。
class User attr_reader :name def initialize(name, weight) @name = name @weight = weight end def heavier_than_protected?(other_user) other_user.weight_protected < @weight end def heavier_than_private?(other_user) other_user.weight_private < @weight end protected def weight_protected @weight end private def weight_private @weight end end alice = User.new('Alice', 50) bob = User.new('Bob', 60) p alice.heavier_than_protected?(bob) #=> false p alice.heavier_than_private?(bob) #=> error private method called