Ruby – 从对象内调用setter
发布时间:2020-12-16 23:26:14 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why do Ruby setters need “self.” qualification within the class?3个 我一直在编写实用程序员编程Ruby的书,并想知道是否可以在类中调用setter方法而不是直接分配给实例变量. class BookInStock attr_reader :isbn,:price def initialize (
参见英文答案 >
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |