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... 回答1: For your question, one could actually do: @users.collect(&:score).sum.to_f/@users.length if @users.length > 0 Earlier I thought, @users