rlsaj
rlsaj

Reputation: 735

Sum of values in loop and keeping highest value

I am trying to calculate the shipping dimensions of multiple products. I want to return the largest value of @tempLength and @tempWidth and sum up all @tempHeights in my loop:

@tempLength = 0
@tempWidth = 0
@tempHeight = 0

params[:rate][:items].each do |item|
  item = item[:product_id]
  puts "Item details"
  puts item
  @productDimensions = Product.where(:product_id => item).first
  @tempLength = @productDimensions.length
  @tempWidth = @productDimensions.width
  @tempHeight = @productDimensions.height
  # tempLength = maximum length value
  # tempWidth = maximum width value
  # tempHeight = sum of all heights
end

I know I have to use sum(&:symbol), but I'm stuck. What's the best approach?

Upvotes: 0

Views: 77

Answers (2)

Stephan Wiehr
Stephan Wiehr

Reputation: 166

Maybe another suggestion that may result in better performance:

@tempLength = 0
@tempWidth = 0
@tempHeight = 0
product_ids = []
params[:rate][:items].each do |item|
  product_ids << item[:product_id]
end

# Filter products according to collected product_ids
@products = Product.where(:product_id => product_ids)

# Let ActiveRecord do the work
@tempLength = @products.sum('length')
@tempWidth  = @products.sum('width')
@tempHeight = @products.maximum('height')

# @tempLength = total of all tempLength values
# @tempWidth = total of all tempHeight values
# @tempHeight = keep highest value

Upvotes: 1

widjajayd
widjajayd

Reputation: 6253

here probably can help

@tempLength = 0
@tempWidth = 0
@tempHeight = 0
params[:rate][:items].each do |item|
  item = item[:product_id]
  puts "Item details"
  puts item
  @productDimensions = Product.where(:product_id => item).first
  @tempLength = @tempLength + @productDimensions.length
  @tempWidth  = @tempWidth  + @productDimensions.width
  if @productDimensions.height > @tempHeight
    @tempHeight = @productDimensions.height 
  end
end
# @tempLength = total of all tempLength values
# @tempWidth = total of all tempHeight values
# @tempHeight = keep highest value

Upvotes: 3

Related Questions