Counting distinct and duplicate attribute values in an array

Posted by keruilin on Stack Overflow See other posts from Stack Overflow or by keruilin
Published on 2010-05-16T19:37:23Z Indexed on 2010/05/16 19:40 UTC
Read the original article Hit count: 182

Filed under:
|
|
|

I have an array of users that's sorted in descending order based on total_points.

I need to find the rank of each user in that array. The issue is that more than one user can have the same total points and, thus, the same rank. For example, three users could be in 3rd place with 200 Points. Here's my current code:

class Leader < ActiveRecord::Base  
  def self.points_leaders
    all_leaders = all_points_leaders # returns array of users sorted by total_points in desc order
    all_leaders_with_rank = []

    all_leaders.each do |user|
      rank = all_leaders.index(user)+1
      all_leaders_with_rank << Ldr.new(rank, user) # Ldr is a Struct
    end

    return all_leaders_with_rank
  end
end

How must I modify the code so that the correct rank is returned, and not just the value of the index position?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about arrays