Ruby 计算数组中对象的属性的平均值

来源:互联网 发布:淘宝店引流量方法 编辑:程序博客网 时间:2024/05/19 23:23
@students = Student.all# 计算所有学生的平均成绩(score)avg_score = @students.collect(&:score).sum.to_f / @students.length if @users.length > 0

这其中&符 代替了: @students.collect{ |stu| stu.score}.

更多查阅:http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/


原文:http://stackoverflow.com/questions/984995/ruby-on-rails-field-average

原创粉丝点击