6

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

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

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

有没有像@users.average(:score) 这样的东西?我想我在数据库字段中遇到过类似的事情,但我需要它来为集合工作......

4

4 回答 4

13

对于您的问题,实际上可以这样做:

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

早些时候我认为,@users.collect(&:score).average 会起作用。对于数据库字段, User.average(:score) 将起作用。您还可以像其他 activerecord 查询一样添加 :conditions。

于 2009-06-12T04:34:42.070 回答
2

我用这种方法来扩展我们的朋友数组:

class Array 
  # Calculates average of anything that responds to :"+" and :to_f
  def avg 
    blank? and 0.0 or sum.to_f/size 
  end
end
于 2009-06-12T06:44:40.480 回答
2

这是一个小片段,不仅可以获得平均值,还可以获得标准偏差。

class User
  attr_accessor :score
  def initialize(score)
    @score = score
  end
end

@users=[User.new(10), User.new(20), User.new(30), User.new(40)]

mean=@users.inject(0){|acc, user| acc + user.score} / @users.length.to_f
stddev = Math.sqrt(@users.inject(0) { |sum, u| sum + (u.score - mean) ** 2 } / @users.length.to_f )
于 2009-06-12T07:17:31.633 回答
2

你可以在这里用这个

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-average

于 2011-01-16T23:18:58.683 回答