How do I add each price to the current price?

跟風遠走 提交于 2019-12-12 23:05:38

问题


I am trying to write a method that will find each price and add it to the current price.

Quote.rb:

class Quote < ActiveRecord::Base
  has_many :items

  def calc_price
    sum = 0
    items.each do |item|
      item.price
    end
    sum = (item1 + item2 etc)
  end
end

回答1:


Here's a nice feature about the more current Rubies:

values = [1,2,3,4,5]
values.inject(:+) # => 15

Now, that said, you're working with a database, so have it sum the records. From the documentation:

Calculates the sum of values on a given column. The value is returned with the same data type of the column, 0 if there’s no row. See calculate for examples with options.

Person.sum('age') # => 4562



回答2:


items.inject(0){|sum, item| sum += item.price}



回答3:


In this case, you can offload the calculation to the database.

def total_price
  items.sum('price')
end

Reference: http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-sum




回答4:


You need to sum the price within the .each loop

class Quote < ActiveRecord::Base
  has_many :items

  def calc_price
    sum = 0
    items.each do |item|
      sum += item.price
    end
  end
end

You can further compact that loop to a single line using

items.each {|item| sum += item.price}



回答5:


How about

items.map(&:price).inject(0, :+)

The map part maps the items array to an array of prices and the inject part starts with 0 and adds each element of the price array.

Mapping StackOverflow question

inject docs

inject examples



来源:https://stackoverflow.com/questions/19462024/how-do-i-add-each-price-to-the-current-price

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!