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.
Joshua M. (Guest)
on 2008-10-03 16: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
Stefano C. (Guest)
on 2008-10-03 16:24
(Received via mailing list)
Alle Friday 03 October 2008, Joshua M. 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
James C. (Guest)
on 2008-10-03 16: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 }
Farrel L. (Guest)
on 2008-10-03 16:28
(Received via mailing list)
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
Lloyd L. (Guest)
on 2008-10-03 16:50
Is that an echo I hear?  :)
Erik V. (Guest)
on 2008-10-03 21: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.