I've been working through the Pragmatic Programmers 'Programming Ruby' book and was wondering if it was possible to call a setter method within a class rather than just assigning to the instance variable directly.
class BookInStock
attr_reader :isbn, :price
def initialize (isbn, price)
@isbn = isbn
@price = Float(price)
end
def price_in_cents
Integer(price*100 + 0.5)
end
def price_in_cents=(cents)
@price = cents/100.0
end
def price=(dollars)
price = dollars if dollars > 0
end
end
In this case I am using a setter to ensure that the price can't be negative. What i want to know is if it is possible to call the price setter from within the price_in_cents setter so that I wont have to write extra code to ensure that the price will be positive.
Thanks in advance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With