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
To count the elements in an array that match a condition: Use the filter() method to iterate over the array. On each iteration, check if the condition is met. Access the length property on the array to get the number of elements that match the condition.
You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.
Use len() & List comprehension to count elements in list based on conditions. We can use list comprehension to create a new list of elements that satisfies our given condition and then get the length of this new list to find out number of elements in original list that satisfies our condition i.e.
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)
Array#select will get the job done.
Docs: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-select
You might do something like this:
number_of_users = @friend_comparisons.select{|friend| friend.counter >= 5 }.size
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With