6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[ruby] プライベートなクラスメソッドを定義してクラスメソッドから呼びたいとき

Last updated at Posted at 2017-06-18

以下のような定義の仕方だとプラベートインスタンスメソッドのfugaが定義されるため、クラスメソッドのhogeからは呼べません。

class Hoge
  def self.hoge
    p "hogehoge"
    fuga
  end
  private
    def fuga
      p "fugafuga"
    end
end

Hoge.hoge
# => "hogehoge"
# => NameError: undefined local variable or method `fuga' for Hoge:Class
Hoge.fuga
# => NoMethodError: undefined method `fuga' for Hoge:Class

クラスメソッドからプライベートなメソッドを呼びたい場合、
プライベートなクラスメソッドを定義して、以下のようにクラスメソッドのfugaを定義してからprivate_class_methodfugaをプライベートクラスメソッドにします。

class Hoge
  def self.hoge
    p "hogehoge"
    fuga
  end
  def self.fuga()
    p "fugafuga"
  end
  private_class_method :fuga
end

Hoge.hoge
# => "hogehoge"
# => "fugafuga"
Hoge.fuga
# => NoMethodError: private method `fuga' called for Hoge:Class
6
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?