Count if there is more than 1 occurrence in a 2d array in Ruby
I've got a sorted array:
array = [[4, 13], [1, 12], [3, 8], [2, 8], [0, 3]]
Which shows me a position (array[n][0]) and the number of occurrences of that position (array[n][1]).
I need to test to see if more than one item in the array has the same number of occurrences as the last item.
I thought I might be able to do it with this:
array.detect {|i| i[1] == array.last[1] }.length
But it returns 2 for the above array, and seems to also return 2 for the following array:
array = [[4, 13], [1, 12], [3, 8], [2, 3], [0, 3]]
When I run it without length it always returns the first occurrence.
Is there a way to get this to count the occurrences?
EDIT:
Sorry, will ask my follow up question in a ne开发者_如何学编程w question.
Try using find_all
instead of detect
. detect
returns the first match. In your first example, that's array[3]
, which is another array of length 2. That's why it's returning 2 (it should always be returning 2 or nil for your arrays). find_all
will return an array of the matches (instead of the first match itself), and its length will be the value you want.
Here's a clearer way of doing what you want, with none of the associated worries.
array.count{|i| i[1] == array.last[1]}
精彩评论