如何在初始化方法中干掉我的ruby异常?
发布时间:2020-12-17 01:31:20 所属栏目:百科 来源:网络整理
导读:我正在使用Product类在 Ruby中编写程序.每当使用错误类型的参数初始化Product时,我都会引发一些异常.有没有办法可以减少我提出的异常(我甚至指的是正确的?)我很感激你的帮助.代码如下: class Product attr_accessor :quantity,:type,:price,:imported def
我正在使用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,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,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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |