Ruby on rails 对数组中不同和重复的属性值进行计数
我有一个用户数组,它根据总积分按降序排序 我需要找到该数组中每个用户的排名。问题是,多个用户可以拥有相同的总分,因此排名相同。例如,三名用户可能以200分排名第三。以下是我当前的代码:Ruby on rails 对数组中不同和重复的属性值进行计数,ruby-on-rails,arrays,struct,count,Ruby On Rails,Arrays,Struct,Count,我有一个用户数组,它根据总积分按降序排序 我需要找到该数组中每个用户的排名。问题是,多个用户可以拥有相同的总分,因此排名相同。例如,三名用户可能以200分排名第三。以下是我当前的代码: class Leader < ActiveRecord::Base def self.points_leaders all_leaders = all_points_leaders # returns array of users sorted by total_points in desc
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
我必须如何修改代码以便返回正确的排名,而不仅仅是索引位置的值?边界暴力方法将是对现有代码的简单更改
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
创建一个由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