Ruby on rails 3 获取满足特定条件的数组项计数
我有一个名为@friend\u comparations的数组,其中填充了许多用户对象。然后,我使用以下方法对数组进行排序:Ruby on rails 3 获取满足特定条件的数组项计数,ruby-on-rails-3,Ruby On Rails 3,我有一个名为@friend\u comparations的数组,其中填充了许多用户对象。然后,我使用以下方法对数组进行排序: @friend_comparisons.sort! { |a,b| b.completions.where(:list_id => @list.id).first.counter <=> a.completions.where(:list_id => @list.id).first.counter } 数组#select将完成任务 文件: 您可以
@friend_comparisons.sort! { |a,b| b.completions.where(:list_id => @list.id).first.counter <=> a.completions.where(:list_id => @list.id).first.counter }
数组#select将完成任务
文件:
您可以这样做:
number_of_users = @friend_comparisons.select{|friend| friend.counter >= 5 }.size
您可以直接使用数组#计数
@friend_comparisons.count {|friend| friend.counter >= 5 }
文件:
(与ruby 1.9.3相同)我是否需要遍历每个数组项并检查条件,然后在满足条件的情况下在计数器上添加一个勾号,或者是否有不使用迭代计数器的方法来执行此操作?这很有效,但如果只是查找数字,则计数会更好。(borod108的回答)如果
@friend\u comparations
是ActiveRecord关系,您可以(应该)使用size
而不是count
来避免不必要的查询
@friend_comparisons.count {|friend| friend.counter >= 5 }