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 回答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