我正在用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)