参见英文答案 >
Why do Ruby setters need “self.” qualification within the class?3个
我一直在编写实用程序员编程Ruby的书,并想知道是否可以在类中调用setter方法而不是直接分配给实例变量.
我一直在编写实用程序员编程Ruby的书,并想知道是否可以在类中调用setter方法而不是直接分配给实例变量.
- 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
在这种情况下,我使用一个setter来确保价格不能为负.我想知道的是,是否可以从price_in_cents setter中调用price setter,这样我就不必编写额外的代码来确保价格为正.
提前致谢
解决方法
使用self.setter,即:
- def price_in_cents=(cents)
- self.price = cents/100.0
- end