输出十进制/浮点数组轨的总和

我有以下内容,我认为可以获取数组的总和,但没有:

<% @orders.each do |order| %>
   <% if Product.exists?(sku: order.line_items.where().map {|li| li.sku }) %>
      <%= order.line_items.where(vendor_name: @vendor.vendor_name).map do |li| %>
          <% if Product.exists?(sku: li.sku) %>
              <% product = Product.find_by(sku: li.sku ) %>
              <% ((li.store_price.to_d * li.store_fulfillable_quantity) - (product.production_price * li.store_fulfillable_quantity)) * (0.70) %>
          <% end %>
       <% end.compact.sum %>
   <% end %>
<% end %>

输出类似于:

25.21 25.21 12.66 5.33 12.66 9.01

我需要添加这些数字。我该如何使用小数/浮点数?

当我使用

<%= @orders.each do |order| %>

我得到undefined method + for nilclass的行,不是零,但显然我缺少求和方式的一些因素。

p82591942 回答:输出十进制/浮点数组轨的总和

<%= @orders.map do |order| %>
   <% if Product.exists?(sku: order.line_items.where().map {|li| li.sku }) %>
      <% order.line_items.where(vendor_name: @vendor.vendor_name).map do |li| %>
          <% if Product.exists?(sku: li.sku) %>
              <% product = Product.find_by(sku: li.sku ) %>
              <% ((li.store_price.to_d * li.store_fulfillable_quantity) - (product.production_price * li.store_fulfillable_quantity)) * (0.70) %>
          <% end %>
       <% end.compact.sum %>
   <% end %>
<% end.compact.sum %>

这是我如何工作的

, 数组中的

方法reduce,用于减少收藏价值:

array.compact.reduce(:+)
# => Sum of array

有关reduce

的更多信息
本文链接:https://www.f2er.com/3130486.html

大家都在问