Getting a Count of Array Items that Meet a Certain Criteria

ruby-on-rails-3

I have an array called @friend_comparisons which is populated with a number of user objects. I then sort the array using the following:

@friend_comparisons.sort! { |a,b| b.completions.where(:list_id => @list.id).first.counter <=> a.completions.where(:list_id => @list.id).first.counter }

This is sorting the array by a certain counter associated with each user (the specifics of which are not important to the question).

I want to find out how many user objects in the array have a counter that is greater than a certain number (let's say 5). How do I do this?

Here is how I am currently solving the problem:

@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

Best Answer

You can use Array#count directly.

@friend_comparisons.count {|friend| friend.counter >= 5 }

Docs: http://ruby-doc.org/core-2.2.0/Array.html#method-i-count

(same for ruby 1.9.3)

Related Topic