コンテンツにスキップ

メソッドの可視性と組み込み関数

メソッドの可視性

  • public : どのインスタンスからも実行できる(デフォルト)
  • protected : 自分自身、またはサブクラスのインスタンスから実行できる
  • private : レシーバをつけた呼び出しはできない
class Baz1
  def public_method1; 1; end

  public
  def public_method2; 2; end

  protected
  def protected_method1; 1; end
  def protected_method2; 2; end

  private
  def private_method1; 1; end
end

Baz1.new.public_method1     # => 1
Baz1.new.public_method2     # => 2
Baz1.new.protected_method1  # => NoMethodError
Baz1.new.protected_method2  # => NoMethodError
Baz1.new.private_method1    # => NoMethodError

順序を考慮しない場合は、メソッド名をシンボルで指定することも可能。

class Baz1
  def public_method1; 1; end
  def public_method2; 2; end
  def protected_method1; 1; end
  def protected_method2; 2; end
  def private_method1; 1; end

  public :public_method1, :public_method2
  protected :protected_method1, :protected_method2
  private :private_method1
end

メソッドの可視性はクラスに結びついているため、サブクラスで自由に変更できる。

def Baz1Ext < Baz1
  public :private_method1
end

Baz1.new.private_method1      # => NoMethodError
Baz1Ext.new.private_method1   # => nil

private メソッドの振る舞いの注意

class Baz2
  def public_method1
    private_method1       # レシーバを省略
  end

  def public_method2
    self.private_method1  # Ruby2.7以降は実行可能
  end

  private

  def private_method1; end
end

Baz2.new.private_method1  # => NoMethodError
Baz2.new.public_method1   # => nil
Baz2.new.public_method2   # => nil