Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails field average?

Is there an easy way to obtain the average of an attribute in a collection?

For instance, each user has a score.

Given a collection of user(s) (@users), how can you get the average score for the group?

Is there anything like @users.average(:score)? I think I came across something like this for database fields, but I need it to work for a collection...

like image 273
David Avatar asked Jun 12 '09 04:06

David


1 Answers

For your question, one could actually do:

@users.collect(&:score).sum.to_f/@users.length if @users.length > 0

Earlier I thought, @users.collect(&:score).average would have worked. For database fields, User.average(:score) will work. You can also add :conditions like other activerecord queries.

like image 165
Ryan Oberoi Avatar answered Oct 11 '22 15:10

Ryan Oberoi