小编Bri*_*ian的帖子

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

我正在用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
Run Code Online (Sandbox Code Playgroud)

ruby dry raise

4
推荐指数
1
解决办法
4353
查看次数

标签 统计

dry ×1

raise ×1

ruby ×1