How to get an item's rank in an ActiveRecord collection, with ties?
<p>I've got a collection of @players, ordered by total_points. I'm trying to figure out what position a specific @player is ranked in the collection of @players.</p>

<p>Example: there are 5 players, here are their total_points:</p>

<ul>
<li>Player 1: 20 points </li>
<li>Player 2: 20 points </li>
<li>Player 3: 15 points </li>
<li>Player 4: 15 points </li>
<li>Player 5: 15 points</li>
</ul>

<p>Given that we measure ties like this:</p>

<ul>
<li>Player 1: Tied for 1st</li>
<li>Player 2: Tied for 1st</li>
<li>Player 3: Tied for 3rd</li>
<li>Player 4: Tied for 3rd</li>
<li>Player 5: Tied for 3rd</li>
</ul>

<p>What's the easiest way to <strong><em>only</em></strong> show Player 4's rank? Is this possible without iterating through the entire collection? I have an idea of how I would print out the entire list by checking if the previous iterator's total_score is the same, but I don't need to display the whole list, just the rank for the current player.</p>

<p>In my app, there are going to be close to a thousand players, so I'm trying to find a method that will be fast to calculate.</p>

<p>EDIT:</p>

<p>Here's what I've come up with based on @max's answer:</p>

<pre><code> @grouped_players = Player.all.reorder(total_points: :desc).group(:total_points).count
 our_rank = 0
 tied = false
 @grouped_players.each do |points, count|
   if points &gt; @player.total_points
     our_rank += count
   end
   if points == @player.total_points
     our_rank += 1
     if count &gt; 1
       tied = true
     end
     break
   end
 end

 puts our_rank
 puts tied
</code></pre>

<p>Anyone have a more elegant solution?</p>