🖥
When you can not assign an accessor variable with Ruby | attr_accessor
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
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
公開日時
2019-04-16
Discussion