🖥

When you can not assign an accessor variable with Ruby | attr_accessor

2019/04/16に公開

problem

If you write accessor = [value] in initialize. Ruby seems to be an assignment to a local variable.

 class Book attr_accessor :price def initialize price = 1080 end end 

Even when calling the accessor. price = 1080 which should be assigned as initial value does not come out.

 book = Book.new p book.price # => nil 

Solution

Write self.price = xxxx instead of price = xxxx .

 class Book attr_accessor :price def initialize self.price = 1080 end end 

 book = Book.new p book.price # => 1080 

This is ok.

environment

  • ruby 2.0.0

Original by

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

About

About this translattion

チャットメンバー募集

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

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-04-16

Discussion