Bassman Bassman - 1 year ago 139
Ruby Question

Rails: Remove Curly Braces in Array

I have the following code:

@temp = SalesOrder.where("status > ?", 0).ids
items = SalesOrderItem.where(sales_order_id: @temp).where.not(product_id: nil)

total = items.to_a.group_by(&:product_id).map do |product_id, quantity|
{:product_name => Product.find(product_id.to_i).name,
:quantity => quantity.sum { |q| q.quantity.to_f } }
end

@top_five = total.sort_by { |h| h[:quantity] }.reverse!


@top_five
produces this array:

[{:product_name => "Six", :quantity => 1300.0},
{:product_name => "Plastic Tumbler 620ml", :quantity => 1205.0},
{:product_name => "Product Four", :quantit y=> 1110.0},
{:product_name => "Product Five", :quantity => 510.0},
{:product_name => "Fiber Optic Cable", :quantity => 200.0}]


I need it to be in this format

{"Football" => 10, "Basketball" => 5}


or this

[["Football", 10], ["Basketball", 5]]

Answer Source
@temp = SalesOrder.where("status > ?", 0).ids
items = SalesOrderItem.where(sales_order_id: @temp).where.not(product_id: nil)
total = items.to_a.group_by(&:product_id).each_with_object({}) do |(product_id, quantity), total|
  total[Product.find(product_id.to_i).name] = quantity.map(&:quantity).map(&:to_f).sum
end
@top_five = total.sort_by { |k, v| v }.reverse!

Check this. It should work. If any errors, ping me, I will update it

PS: your code is not optimized at all. All of this could be done with single SQL query, but the logic is pretty hard to write this query without debugging

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download