Ruby on rails如何在数组中找到与第一个项目相匹配的项目

时间:2016-08-23 03:21:15

标签: ruby-on-rails ruby

我有一个排行榜数组,看起来像这样:

[{:member=>"1", :score=>7.0, :rank=>1}, {:member=>"5", :score=>6.0, :rank=>2}, {:member=>"4", :score=>5.0, :rank=>3}, {:member=>"3", :score=>4.0, :rank=>4}, {:member=>"2", :score=>3.0, :rank=>5}]

我还有一组活动用户ID [3,5]

如何获取排名最高的活跃用户的成员编号并将其分配给变量?排行榜数组将始终按排名顺序排列。

4 个答案:

答案 0 :(得分:2)

一种方法是将数组减少到只有:member也在活动用户ID数组中的条目,然后获取该数组的第一个元素:

leaderboard = [...]
active_user_ids = [3,5]

leaderboard.take_while{ |m| active_user_ids.include?(m[:member].to_i) }.first

答案 1 :(得分:1)

leaderboard = [{:member=>"1", :score=>7.0, :rank=>1},
               {:member=>"5", :score=>6.0, :rank=>2},
               {:member=>"4", :score=>5.0, :rank=>3},
               {:member=>"3", :score=>4.0, :rank=>4},
               {:member=>"2", :score=>3.0, :rank=>5}]

active_members = [3,5]

highest_ranked_active_member = leaderboard.
  select { |h| active_members.include? h[:member].to_i }.
  min_by { |h| h[:rank] }[:member]
  #=> "5"  

答案 2 :(得分:1)

在这种情况下,我喜欢在查询数据时创建可重用的lambda以重用代码。

active_members = [3,5]
active_member  = -> member { active_members.include? member[:member].to_i }
member_score   = -> member { member[:score] }

leader_board = ...

# Find first active_member:
p leader_board.find(&active_member) #=> {:member=>"5", :score=>6.0, :rank=>2}
# Find active member with lowest and highest score:
p leader_board.select(&active_member).minmax_by(&member_score) #=> [{:member=>"3", :score=>4.0, :rank=>4}, {:member=>"5", :score=>6.0, :rank=>2}]

答案 3 :(得分:1)

list = [
  {:member=>"1", :score=>7.0, :rank=>1}, 
  {:member=>"5", :score=>6.0, :rank=>2}, 
  {:member=>"4", :score=>5.0, :rank=>3}, 
  {:member=>"3", :score=>4.0, :rank=>4}, 
  {:member=>"2", :score=>3.0, :rank=>5}
]

list.select { |item| [3,5].include? item[:member].to_i }.max { |item| item[:rank] }[:member] => "3"