Reputation: 6029
For me i could not think of better way but i believe there is one. Is there a ruby way (meaning: elegant way) to do the following method implementation?
def total(items)
sum = 0
items.each do |item|
sum += item.value
end
sum
end
Upvotes: 0
Views: 100
Reputation: 96934
map
to get the values, then reduce
them using addition:
def total(items)
items.map(&:value).reduce(:+)
end
Upvotes: 3
Reputation: 21791
items.inject(0) { |memo,item| memo + item.value }
It may seem that no need to have 0 as initial value, but in case when array is empty it will return this initial value.
Second approach:
items.map(&:value).inject(0,:+)
Upvotes: 3
Reputation: 15010
def total(items)
items.inject(0) do |total, item|
total + item.value
end
end
Upvotes: 1
Reputation: 230316
You can do this, for example
items.reduce{|sum, el| sum + el.value}
Upvotes: 2