Ruby で private_class_method を使ってみる
Ruby
Published: 2019-07-16

やったこと

Ruby で private_class_method を使ってみます。

確認環境

$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]

調査

ruby-private-class-method.rb

class Sample
  def self.hoge
    p __method__
  end

  def self.hoge2
    p __method__
  end

  def hoge3
    p __method__
  end

  private_class_method :hoge
end

検証

$ irb
...

irb(main):007:0> require './ruby-private-class-method'
=> true
irb(main):008:0> Sample.hoge
Traceback (most recent call last):
        4: from /Users/hogehoge/.rbenv/versions/2.6.3/bin/irb:23:in `<main>'
        3: from /Users/hogehoge/.rbenv/versions/2.6.3/bin/irb:23:in `load'
        2: from /Users/hogehoge/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
        1: from (irb):8
NoMethodError (private method `hoge' called for Sample:Class)
Did you mean?  hoge2
irb(main):009:0> Sample.hoge2
:hoge2
=> :hoge2
irb(main):010:0> Sample.new.hoge3
:hoge3
=> :hoge3

参考