2009-06-12 9 views
5

コレクション内の属性の平均を簡単に取得する方法はありますか?Ruby on Railsフィールド平均?

たとえば、各ユーザーにはスコアがあります。

ユーザーの集まり(@users)があれば、グループの平均得点をどのように得ることができますか?

@ users.average(:score)のようなものはありますか? 1が実際に行うことができ、私はデータベースフィールドのためにこのようなものに出くわしたと思うが、私はそれがコレクションのために働く必要があります...あなたの質問のために

答えて

12

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

以前の私は思った、@users .collect(&:score)。平均はうまくいきました。データベースフィールドの場合、User.average(:score)が動作します。他のアクティブレコードのような条件を追加することもできます。

私はこの方法で私たちの友人アレイを拡張するために使用
+0

ここで非常に素晴らしいこれを使用することができます。 &in:スコアは何をしますか? – David

+0

アンパサンド演算子は、次のものに代わるものです。@ users.collect {| user | user.score} ウェブ上で詳しく読む: http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/ –

+0

非常に素晴らしい。 –

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 
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)] 

[email protected](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)