module_function を使ってみる (Ruby)
Ruby
Published: 2019-10-07

やったこと

module_function を使ってみます。

確認環境

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

調査

module-function.rb

module Sample1
  def hoge1
    'hoge1'
  end
  module_function :hoge1

  def hoge2
    'hoge2'
  end
end

class Sample2
  include Sample1
end

p Sample1.hoge1

p Sample2.new.hoge2
p Sample2.new.hoge1

出力結果

$ ruby module-function.rb
"hoge1"
"hoge2"
Traceback (most recent call last):
module-function.rb:19:in `<main>': private method `hoge1' called for #<Sample2:0x00007fd48b8766c8> (NoMethodError)
Did you mean?  hoge2

参考