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 Amos 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

Ryan Bigg wrote:

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

will also do the trick

Something like this?

total_comments = posts.inject(0) { |sum, post| sum + post.comments.size
}
--
Posted via http://www.ruby-forum.com/.

>

--
Ryan Bigg
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
Ryan Bigg wrote:

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.

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