LoginSignup
0
1

More than 5 years have passed since last update.

インスタンスメソッド内でのself変数の扱い

Last updated at Posted at 2016-08-02

インスタンスメソッド内で、メソッドのレシーバ自身を参照するには、特別なselfという変数を使う。以下の例では、helloメソッドをhello2メソッドから呼び出している。

class HelloWorld
  def initialize(myname='Ruby')
    @name = myname
  end

  def hello
    puts "Hello ,world. I am #{@name}."
  end

  def hello2
    self.hello #インスタンスメソッドのhelloが呼ばれる
  end

end

bob = HelloWorld.new('Bob')
bob.hello  #=> Hello ,world. I am Bob.
bob.hello2 #=> Hello ,world. I am Bob.
0
1
2

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