Ruby on Rails field average?

╄→尐↘猪︶ㄣ 提交于 2019-12-03 01:36:41

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.

I use to extend our friend Array with this method:

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

Here's a little snippet to not only get the average but also the standard deviation.

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 )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!