我有一个名为 @friend_comparisons 的数组,其中填充了许多用户对象。然后我使用以下命令对数组进行排序:
@friend_comparisons.sort! { |a,b| b.completions.where(:list_id => @list.id).first.counter <=> a.completions.where(:list_id => @list.id).first.counter }
这是通过与每个用户关联的特定计数器对数组进行排序(其细节对于问题并不重要)。
我想找出数组中有多少个用户对象的计数器大于某个数字(假设为 5)。我该怎么做呢?
以下是我目前解决问题的方法:
@friends_rank = 1
for friend in @friend_comparisons do
if friend.completions.where(:list_id => @list.id).first.counter > @user_restaurants.count
@friends_rank = @friends_rank + 1
end
end
您可以直接使用Array#count。
@friend_comparisons.count {|friend| friend.counter >= 5 }
Docs: http://ruby-doc.org/core-2.2.0/Array.html#method-i-count http://ruby-doc.org/core-2.2.0/Array.html#method-i-count
(红宝石 1.9.3 相同)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)