本文介绍了Ruby on Rails字段平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的方法来获取集合中属性的平均值吗?

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

例如,每个用户都有一个分数。

For instance, each user has a score.

给定一个用户集合(@users),如何获得该组的平均分数?

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

有什么像@ users.average(:score)?我想我为数据库字段遇到类似这样的东西,但我需要它为一个集合工作

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

推荐答案

你的问题,实际上可以做:

For your question, one could actually do:

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

早些时候我想,@ users.collect(&:score)。对于数据库字段,User.average(:score)将工作。您还可以添加:条件,如其他activerecord查询。

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.

这篇关于Ruby on Rails字段平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:35