Iterate over array and add numbers of each object

Hi all

number = 0;
objects.each do |o|
number += o.some_number
end
return number

I guess there’s a much more beautiful way for this, or isn’t? Something
like collect or so…

Thanks :slight_smile:
Josh

Alle Friday 03 October 2008, Joshua M. ha scritto:

Thanks :slight_smile:
Josh

If objects is an array, or any other thing which mixes-in the Enumerable
module, you can use inject:

objects.inject(0){|tot, o| tot + o.some_number}

Stefano

number = 0;
objects.each do |o|
number += o.some_number
end
return number

I guess there’s a much more beautiful way for this, or isn’t? Something
like collect or so…

number = objects.inject(0) { |sum, obj| sum + obj.some_number }

2008/10/3 Joshua M. [email protected]:

Hi all

number = 0;
objects.each do |o|
number += o.some_number
end
return number

This is what inject is for.

number = objects.inject(0) do |sum,o|
sum += o.some_number
end

Farrel

require “facets”

number = objects.map(&:some_number).sum

gegroet,
Erik V.

Is that an echo I hear? :slight_smile: