2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ruby | attr_accessor + initialize でアクセサ変数に代入できない時

Last updated at Posted at 2015-12-15

問題

initialize の中で accessor = [value] って書くと。
Ruby にはローカル変数への代入だと思われる。

class Book
  attr_accessor :price

  def initialize
    price = 1080
  end
end

アクセサを呼び出しても。
初期値として代入したはずの price = 1080 が出てこない。

book = Book.new
p book.price

# => nil

解決

price = xxxx ではなく
self.price = xxxx って書くこと。

class Book
  attr_accessor :price

  def initialize
    self.price = 1080
  end
end
book = Book.new
p book.price

# => 1080

これでオーケー。

環境

  • ruby 2.0.0

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?