2010-05-16 61 views
0

我有一个基于total_points以降序排列的用户数组。计算数组中不同和重复的属性值

我需要找到该阵列中每个用户的等级。问题在于不止一个用户可以拥有相同的总分,因此具有相同的等级。例如,三位用户可能以200分位居第三。这里是我当前的代码:

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 

我该怎么修改代码,以便正确的等级返回,而不是只索引位置的值?

回答

0

borderline-brute-force方法将对现有代码进行简单更改。

rank = 1 
all_leaders.each_with_index do |user, idx| 
    # If this user has a different point total than the previous user in the list, 
    # bump the rank. 
    if idx > 0 && all_leaders[idx - 1].total_points != user.total_points 
    # The point of using the idx as an offset here is so that you end up with 
    # T1 
    # T1 
    # T3 
    # in the case of a tie for first. 
    rank = idx + 1 
    end 
    all_leaders_with_rank << Ldr.new(rank, user) # Ldr is a Struct 
end 
0

创建一个唯一点数组(按all_points_leaders函数排序)。使用该数组的索引+1作为用户的等级。

def self.points_leaders 
    all_points = all_points_leaders.map {|user| user.total_points }.uniq 
    all_points_leaders.map do |user| 
    rank = all_points.index(user.total_points) + 1 
    Ldr.new(rank, user) 
    end 
end