Forum: Ruby Iterate over array and add numbers of each object

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Fc582698581884352e745d1d4c64699d?d=identicon&s=25 Joshua Muheim (josh)
on 2008-10-03 14:18
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 :-)
Josh
C40020a47c6b625af6422b5b1302abaf?d=identicon&s=25 Stefano Crocco (crocco)
on 2008-10-03 14:24
(Received via mailing list)
Alle Friday 03 October 2008, Joshua Muheim ha scritto:
>
> Thanks :-)
> 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
53581739a445ad78250a676dabddf55f?d=identicon&s=25 James Coglan (Guest)
on 2008-10-03 14:26
(Received via mailing list)
> 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 }
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel Lifson (Guest)
on 2008-10-03 14:28
(Received via mailing list)
2008/10/3 Joshua Muheim <forum@josh.ch>:
> 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
84dc575c33a123789521d53cad0f62ae?d=identicon&s=25 Lloyd Linklater (lloyd)
on 2008-10-03 14:50
Is that an echo I hear?  :)
6b0967f63d03e99b6c07a3f5ed224c77?d=identicon&s=25 Erik Veenstra (Guest)
on 2008-10-03 19:24
(Received via mailing list)
require "facets"

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

gegroet,
Erik V.
This topic is locked and can not be replied to.