@Override
public boolean onKeyDownPreview(char key, int modifiers) {
switch (key) {
case KeyCodes.KEY_ESCAPE:
hide();
break;
}
return true;
}
На ваш вопрос, на самом деле можно было бы сделать:
@users.collect(&:score).sum.to_f/@users.length if @users.length > 0
Раньше я думал, что @ users.collect (&: score) .average сработает. Для полей базы данных будет работать User.average (: score). Вы также можете добавить: условия, как и другие запросы activerecord.
] Я использую для расширения нашего друга Array с помощью этого метода:
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
Вот небольшой фрагмент, чтобы получить не только среднее, но и стандартное отклонение.
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 )