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

···

--
Posted via http://www.ruby-forum.com/.

Alle Friday 03 October 2008, Joshua Muheim ha scritto:

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

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 }

This is what inject is for.

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

Farrel

···

2008/10/3 Joshua Muheim <forum@josh.ch>:

Hi all

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

--
Aimred - Ruby Development and Consulting

require "facets"

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

gegroet,
Erik V.

Is that an echo I hear? :slight_smile:

···

--
Posted via http://www.ruby-forum.com/.