0

I am trying to understand the attr_accessor, and while digging I get pretty confused with the following behaviour:

class Item

    def change_price
        price=(2)
    end

    def price=(value)
        @price = value
    end

    def price
        @price
    end

end

my_item = Item.new
p my_item.price
my_item.change_price
p my_item.price

=> nil
nil

I would expect the price to be set to 2. Clearly I totally misunderstood something that I thought obvious. Would anybody be kind enough to explain me where I am being thick?

Thank you

user3029400
  • 387
  • 1
  • 5
  • 13

1 Answers1

1

Attribute setter (any function trailing with an equal sign) must be called on the explicit receiver. Otherwise, the local variable price is being created and assigned to the value.

Fix:

def change_price
#   price=(2)
    self.price=(2)
end
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160