[英]Multiplication in Ruby on Rails Model of nil values
I have several calculated values as part of my risk.rb model 我有一些计算值作为我的Risk.rb模型的一部分
before_save :calculate_risk
def calculate_risk
self.risk1_total = self.component1 * self.component2 * self.component3
self.risk2_total = self.component4 * self.component5 * self.component6
...
end
I want to be able to create a risk without filling out the form completely thus each of those components would be nil. 我希望能够在不完全填写表格的情况下制造风险,因此每个组成部分都将为零。 So this method creates an error because * is not a valid method for a nil.
因此此方法会产生错误,因为*不是nil的有效方法。 What is the best way to handle this?
处理此问题的最佳方法是什么? I have considered
我考虑过
def calculate_risk
if self.component1.nil? || self.component2.nil? || self.component3.nil?
self.risk1_total = self.component1 * self.component 2 * self.component3
elsif ...
end
However, this is obviously inefficient and repetitive. 但是,这显然是无效的和重复的。 I also considered initializing all of these values, though I do not know the most efficient way of doing this.
我也考虑过初始化所有这些值,尽管我不知道这样做的最有效方法。
You can do something like the following: 您可以执行以下操作:
before_save :calculate_risk
def calculate_risk
self.risk1_total = [self.component1,self.component2,self.component3].compact.inject(:*)
self.risk2_total = [self.component4,self.component5,self.component6].compact.inject(:*)
...
end
This is assuming you want nil values to just be dropped from the calculation. 假设您要从计算中删除nil值。 This will give a result of
nil
if all values are nil
. 这会给的结果
nil
如果所有值均为nil
。 You could replace the nil
s with zeroes if you prefer. 如果愿意,可以将
nil
替换nil
。 You may also be interested in the :reject
method or other cools tools in the Ruby Array and Enumerable classes. 您可能也对Ruby Array和Enumerable类中的
:reject
方法或其他炫酷工具感兴趣。
I hope that helps. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.