LoginSignup
62
46

More than 5 years have passed since last update.

インスタンスメソッド内での @ と self の違い

Last updated at Posted at 2013-09-11

@hoge は、インスタンス変数 @hoge を参照します。
self.hoge は、インスタンスメソッド hoge を呼び出します。
self.hoge = は、インスタンスメソッド hoge= を呼び出します。


attr_accessorhogehoge=を定義しておけば、self.hogeself.hoge=を呼び出せます。

class Clazz
  attr_accessor :hoge

  def initialize(arg)
    @hoge = arg
  end

  def func
    puts self.hoge
  end
end

obj = Clazz.new 'instance var.'
obj.func #-> instance var.

メソッドが定義されていなければ、当然呼び出せません。

class Clazz
  def initialize(arg)
    @hoge = arg
  end

  def func
    puts self.hoge #-> undefined method `hoge' 発生
  end
end

obj = Clazz.new 'instance var.'
obj.func

paiza.ioでコードを公開しました。
ソースをいじりながら確認したい方はどうぞ。

62
46
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
62
46