LoginSignup
1
1

More than 3 years have passed since last update.

Rubyのモジュールのインスタンスメソッドの挙動を実験してみた

Last updated at Posted at 2020-04-05

確認したかったこと

モジュールのインスタンスメソッドからinclude元のクラスのインスタンス変数/メソッドを呼び出すことは可能か?

実験

module TalkActions
  def say_my_name
    puts "I am #{@name}"
  end

  def shout_my_name
    puts "I am #{self.name}!!!!!!!!"
  end
end

class Human
  attr_accessor :name
  include TalkActions
  def initialize(name)
    @name = name 
  end
end

John = Human.new("John")
John.say_my_name # 'I am John'
John.shout_my_name # 'I am John!!!!!!!!'

結論

どちらも呼び出し可能

1
1
0

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
1
1