Iterate over array and add numbers of each object


#1

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


#2

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


#3

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 }


#4

2008/10/3 Joshua M. removed_email_address@domain.invalid:

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


#5

require “facets”

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

gegroet,
Erik V.


#6

Is that an echo I hear? :slight_smile: