Сумма значений в цикле и сохранение наибольшего значения - PullRequest
0 голосов
/ 29 мая 2018

Я пытаюсь рассчитать размеры доставки для нескольких продуктов.Я хочу вернуть наибольшее значение @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 голосов
/ 29 мая 2018

Может быть, еще одно предложение, которое может привести к повышению производительности:

@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
0 голосов
/ 29 мая 2018

тут наверное может помочь

@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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...