Ruby – 从对象内调用setter

前端之家收集整理的这篇文章主要介绍了Ruby – 从对象内调用setter前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Why do Ruby setters need “self.” qualification within the class?3个
我一直在编写实用程序员编程Ruby的书,并想知道是否可以在类中调用setter方法而不是直接分配给实例变量.
  1. class BookInStock
  2.  
  3. attr_reader :isbn,:price
  4.  
  5. def initialize (isbn,price)
  6. @isbn = isbn
  7. @price = Float(price)
  8. end
  9.  
  10. def price_in_cents
  11. Integer(price*100 + 0.5)
  12. end
  13.  
  14. def price_in_cents=(cents)
  15. @price = cents/100.0
  16. end
  17.  
  18. def price=(dollars)
  19. price = dollars if dollars > 0
  20. end
  21.  
  22. end

在这种情况下,我使用一个setter来确保价格不能为负.我想知道的是,是否可以从price_in_cents setter中调用price setter,这样我就不必编写额外的代码来确保价格为正.

提前致谢

解决方法

使用self.setter,即:
  1. def price_in_cents=(cents)
  2. self.price = cents/100.0
  3. end

猜你在找的Ruby相关文章