【发布时间】:2018-11-26 01:47:01
【问题描述】:
我正在计算一个类别的平均投资回报率值。
<% @categories.each do |category| %>
<h3><strong><%= category.name %><strong></h3>
<% @category_products = category.products_by_warehouse_id(params[:id]) %>
<!-- add map/reject below -->
<%@ROI = (@category_products.reduce(0.0) {|acc, item| acc + (item.heritable_sale_price.to_f * item.product_selections.length) / item.purchase_price.to_f }) %>
<p> Category ROI: <%= number_with_precision((@ROI / @category_products.length.to_f), precision:2) %></p>
.....(close tags)......
当缺少财务数据时,该值会抛出 NaN。对于个人价值观,这很好;但是,对于缺少数据的平均值也是如此。
如何将map/reject 添加到我的调用中以丢弃nil 值,并获得可用值的平均值?
@category_products.length.to_f 如果我也走这条路,也必须跳过数组中的空元素,以保持总和和长度一致。 .where(purchase_price: [!nil, ""]).size 之类的东西可能会起作用。
【问题讨论】:
-
您可以尝试使用 where.not 查询您的 category_products:
where.not(heritable_sale_price: nil, product_selections: nil, purchase_price: nil)。如果这不能解决您的问题,则在 item 变量的 reduce 块中调用的任何第二种方法都可以抛出 NoMethodError。 -
如果我单独使用 :purchase_price (:product_selections 是一个联合类,而销售价格是一种方法),这可行,并设置 @category_products_count = category.products_by_warehouse_id(params[:id]).where.not(purchase_price: nil).size%> 的第二个实例以具有一致的值用于平均。提交作为答案?
标签: ruby-on-rails ruby oop view