我有一个名为@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 }
Run Code Online (Sandbox Code Playgroud)
这是通过与每个用户相关联的特定计数器对数组进行排序(其具体细节对于问题不重要).
我想知道数组中有多少用户对象有一个大于某个数字的计数器(比方说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
Run Code Online (Sandbox Code Playgroud)
小智 24
您可以直接使用Array#count.
@friend_comparisons.count {|friend| friend.counter >= 5 }
Run Code Online (Sandbox Code Playgroud)
文档:http://ruby-doc.org/core-2.2.0/Array.html#method-i-count
(同样适用于红宝石1.9.3)
MrT*_*rus 13
数组#select将完成工作.
文档:http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-select
你可能会这样做:
number_of_users = @friend_comparisons.select{|friend| friend.counter >= 5 }.size
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8744 次 |
| 最近记录: |