private_constant を使ってみる (Ruby)
Ruby
Published: 2021-05-08

確認環境

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

調査

a.rb

module Hoge
  class A
    def display
      p 'display'
    end
  end

  class B
    def display
      A.new.display
    end
  end
  private_constant :A
end

p 'Hoge::B'
Hoge::B.new.display
p '----'
p 'Hoge::A'
# 例外発生
Hoge::A.new

出力結果

$ ruby a.rb
"Hoge::B"
"display"
"----"
"Hoge::A"
Traceback (most recent call last):
a.rb:21:in `<main>': private constant Hoge::A referenced (NameError)

参考