当前位置 : 主页 > 编程语言 > ruby >

如何在初始化方法中干掉我的ruby异常?

来源:互联网 收集:自由互联 发布时间:2021-06-23
我正在使用Product类在 Ruby中编写程序.每当使用错误类型的参数初始化Product时,我都会引发一些异常.有没有办法可以减少我提出的异常(我甚至指的是正确的?)我很感激你的帮助.代码如下
我正在使用Product类在 Ruby中编写程序.每当使用错误类型的参数初始化Product时,我都会引发一些异常.有没有办法可以减少我提出的异常(我甚至指的是正确的?)我很感激你的帮助.代码如下:

class Product
  attr_accessor :quantity, :type, :price, :imported

  def initialize(quantity, type, price, imported)
    raise ArgumentError.new("Type must be a string") if type.class != String
    raise ArgumentError.new("Quantity must be greater than zero") if quantity <= 0
    raise ArgumentError.new("Price must be a float") if price.class != Float

    @quantity = quantity
    @type     = type
    @price    = price.round(2)
    @imported = imported
  end
end
惯用的方法是根本不进行类型检查,而是强制传递的对象(使用to_s,to_f等):

class Product
  attr_accessor :quantity, :type, :price, :imported

  def initialize(quantity, type, price, imported)
    raise ArgumentError.new("Quantity must be greater than zero") unless quantity > 0

    @quantity = quantity
    @type     = type.to_s
    @price    = price.to_f.round(2)
    @imported = imported
  end
end

然后,您将获得适当的String / Float / etc.传递的对象的表示,如果他们不知道如何强制转换为那些类型(因为他们没有响应那个方法),那么你将适当地获得NoMethodError.

至于数量检查,这看起来很像验证,你可能想要提取到一个单独的方法(特别是如果它们有很多):

class Product
  attr_accessor :quantity, :type, :price, :imported

  def initialize(quantity, type, price, imported)
    @quantity = quantity
    @type     = type.to_s
    @price    = price.to_f.round(2)
    @imported = imported

    validate!
  end

  private

  def validate!
    raise ArgumentError.new("Quantity must be greater than zero") unless @quantity > 0
  end
end
网友评论