Getting a graph of array elements that satisfy certain criteria

I have an array called @friend_comparisons that is populated with a number of user objects. Then I 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 using a specific counter associated with each user (the features of which are not important for the question).

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

This is how I solve the problem now:

 @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 
+8
ruby-on-rails-3
source share
2 answers

The # select array will do the job.

Documents: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-select

You can do something like this:

 number_of_users = @friend_comparisons.select{|friend| friend.counter >= 5 }.size 
+9
source share

You can directly use Array # count.

 @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)

+17
source share

All Articles