Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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

大佬总结

以上是大佬教程为你收集整理的Ruby – 从对象内调用setter全部内容,希望文章能够帮你解决Ruby – 从对象内调用setter所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。