【问题标题】:Ruby on Rails field average?Ruby on Rails 领域的平均水平?
【发布时间】:2009-06-12 04:28:03
【问题描述】:

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

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

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

有没有类似@users.average(:score) 的东西?我想我在数据库字段中遇到过类似的情况,但我需要它来处理集合...

【问题讨论】:

    标签: ruby-on-rails ruby collections average


    【解决方案1】:

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

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

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

    【讨论】:

    • 非常好。 &:score 中的 & 有什么作用?
    • 与号运算符可替代:@users.collect{ |user| user.score} 在网上阅读更多关于它的信息:eli.thegreenplace.net/2006/04/18/…
    【解决方案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
    

    【讨论】:

      【解决方案3】:

      这里有一个小sn-p,不仅可以得到平均值,还可以得到标准差。

      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 )
      

      【讨论】:

        【解决方案4】:
        猜你喜欢
        • 1970-01-01
        • 2013-08-20
        • 2021-08-27
        • 1970-01-01
        • 2011-03-04
        • 1970-01-01
        • 2020-09-17
        • 2012-08-20
        • 1970-01-01
        相关资源
        最近更新 更多