Ruby – 从对象内调用setter

参见英文答案 > Why do Ruby setters need “self.” qualification within the class?3个
我一直在编写实用程序员编程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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...