Reputation: 1481
I have the following which i thought would get me the sum of the array but doesnt:
<% @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 %>
The output is something like:
25.21 25.21 12.66 5.33 12.66 9.01
I need to add these numbers. How can I do this with the decimals/floats?
When I use
<%= @orders.each do |order| %>
I get undefined method + for nilclass
for the line that is on, and it's not nil but obviously I'm missing some factor on how sum works.
Upvotes: 0
Views: 267
Reputation: 412
method reduce
in arrays designed for getting reduced value of collection:
array.compact.reduce(:+)
# => Sum of array
more info about reduce
Upvotes: 0
Reputation: 1481
<%= @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 %>
Is how i got it to work
Upvotes: 1