lampShade
lampShade

Reputation: 4391

Why can't I set the value of an instance variable like this

I'm trying to understand how to use setter methods in Ruby but I don't understand why this code does not work. Is it not working because I already set he price of book when I created the book object? If I change the line in question to book.price = book.price + 10.00 it works as expected. Why? Why can't I just change the value by just passing in a different parameter?

class BookInStock
    attr_reader   :isbn
    attr_accessor :price

    def initialize(isbn,price)
        @isbn  = isbn
        @price = Float(price) 
    end

    def isbn
        @isbn
    end


    def to_s
        "ISBN: #{@isbn}, price: #{@price}"
    end

end

book = BookInStock.new("isbn",38.5)
puts "The books cost: #{book.price} and the name is: #{book.isbn}"
book.price = book.price 150 # THIS LINE IS BROKEN WHY?
puts "The new price is "
puts "The new price of the book is #{book.price}"

Upvotes: 1

Views: 200

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146053

You do it like this:

book.price = 150

The attribute reader doesn't take any parameters and book.price is not the name of the writer, that's price=.

If you want to pass the new price as a more obvious parameter to your writer, one way would be a call like this:

book.send 'price=', 160

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88378

In short, because

book.price

is a method taking ZERO arguments returning the price of the book. However

book.price=

is a method of ONE argument that sets the value.

The latter method can be called like this:

book.price = 150

You were trying to call the getter with an argument. You can't call book.price 150.

Upvotes: 2

Related Questions