Ruby - 从对象内部调用 setter [英] Ruby - Calling setters from within an object

查看:36
本文介绍了Ruby - 从对象内部调用 setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读 Pragmatic Programmers 'Programming Ruby' 一书,想知道是否可以在类中调用 setter 方法而不是直接分配给实例变量.

I've been working through the Pragmatic Programmers 'Programming Ruby' book and was wondering if it was possible to call a setter method within a class rather than just assigning to the instance variable directly.

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 设置器中调用价格设置器,这样我就不必编写额外的代码来确保价格为正数.

In this case I am using a setter to ensure that the price can't be negative. What i want to know is if it is possible to call the price setter from within the price_in_cents setter so that I wont have to write extra code to ensure that the price will be positive.

提前致谢

推荐答案

使用self.setter,即:

def price_in_cents=(cents)
    self.price = cents/100.0
end

这篇关于Ruby - 从对象内部调用 setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆