循环中的值的总和并保持最高值

时间:2018-05-29 07:12:39

标签: ruby-on-rails ruby

我正在尝试计算多种产品的运输尺寸。我想返回@tempLength@tempWidth的最大值,并在我的循环中总结所有@tempHeight

@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

我知道我必须使用sum(&:symbol),但我被困住了。什么是最好的方法?

2 个答案:

答案 0 :(得分:3)

这里可能有帮助

@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

答案 1 :(得分:1)

也许另一个可能会带来更好表现的建议:

@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