user2769929
user2769929

Reputation: 39

How do I add each price to the current price?

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

Upvotes: 1

Views: 299

Answers (5)

sawa
sawa

Reputation: 168101

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

Upvotes: 2

the Tin Man
the Tin Man

Reputation: 160551

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

Upvotes: 1

Marcelo De Polli
Marcelo De Polli

Reputation: 29291

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

Upvotes: 1

jcm
jcm

Reputation: 1789

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

Upvotes: 0

Anshul Goyal
Anshul Goyal

Reputation: 76897

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}

Upvotes: 0

Related Questions