Ruby - Calling Setters from an Object

I am working on a Ruby Programmers Programmers programmer and wondering if it is possible to call the setter method inside a class, rather than just directly assigning an instance variable.

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 use the setter to ensure that the price cannot be negative. What I want to know is that you can call the price setter with set_in_cents setter so that I don’t have to write additional code to guarantee that the price will be positive.

Thank you in advance

+4
source share
1 answer

Use self.setter , self.setter .:

 def price_in_cents=(cents) self.price = cents/100.0 end 
+6
source

All Articles