Calculations on arrays?

Hi everyone,

I was wondering if there’s an easy way to grab the sum of a column in an
array in ruby? Something that would work like @posts.sum(:column_name).
I know there’s one for Classes, but is there something similar for
arrays?

Thanks!

Dave A. wrote:

Hi everyone,

I was wondering if there’s an easy way to grab the sum of a column in an
array in ruby? Something that would work like @posts.sum(:column_name).
I know there’s one for Classes, but is there something similar for
arrays?

Thanks!

Something like this?

total_comments = posts.inject(0) { |sum, post| sum + post.comments.size
}

posts.map { |p| p.comments.size }.sum

will also do the trick

On Jan 10, 2008 1:07 PM, Jeremy Weiskotten
[email protected]
wrote:

Something like this?

total_comments = posts.inject(0) { |sum, post| sum + post.comments.size
}

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


Ryan B.

Feel free to add me to MSN and/or GTalk as this email.

Ryan B. wrote:

posts.map { |p| p.comments.size }.sum

will also do the trick

On Jan 10, 2008 1:07 PM, Jeremy Weiskotten
[email protected]
wrote:

Something like this?

total_comments = posts.inject(0) { |sum, post| sum + post.comments.size
}

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


Ryan B.
http://www.frozenplague.net
Feel free to add me to MSN and/or GTalk as this email.

Will that work? Array#sum doesn’t exist.

Also, there’s a missing “=” character in my previous reply. Use this
instead:

total_comments = posts.inject(0) { |sum, post| sum += post.comments.size
}

Will that work? Array#sum doesn’t exist.

Ah, I see. Rails adds it to Enumerable. Nice!

I was going to say:

Posts.find(:all).map(&:column_name).sum
or
posts.map(&:column_name).sum

Although Ryan’s example is probably much faster being it doesn’t have to
do a query if the data is already cached.

I don’t have an

It will be even faster if you had a counter_cache on the comments too,
just
another field for a post record to store the number of comments it has.
Built-in feature of Rails.

On Jan 10, 2008 1:18 PM, Russell McConnachie [email protected]
wrote:

I don’t have an

Dave A. wrote:

>


Ryan B.

Feel free to add me to MSN and/or GTalk as this email.

Wow, thanks! I’ll try a couple of these ideas out and see what works
best for me.

Ryan B. wrote:

posts.map { |p| p.comments.size }.sum

will also do the trick

thank you so much! worked well.