如何在数组中查找共享重复属性的元素

时间:2019-07-28 15:22:27

标签: ruby

我有很多球员。每个玩家都被分配了一个score_value。我想找到绑在一起的球员。

该数组为@@players_list,该数组的玩家人数未知。

我尝试过:

@@players_list = [player1, player2, player3]

tied = @@Players_.list.find_all {|p| p.win_value.to_s.count(p.win_value.to_s) > 1}

这不会返回错误,但也不会识别出重复的得分值

tied = @@players_list.select {|p| array{|p| p.score_value}.count(p.score_value) > 1}.uniq 

这将返回:

syntax error, unexpected '}', expecting keyword_end
..._value}.count(p.win_value) > 1}.uniq

2 个答案:

答案 0 :(得分:1)

感谢塞尔吉奥·图伦采夫(Sergio Tulentsev)让我90%的成绩都达到了。这是我想出的似乎可行的方法。

group_by_win_value =  @@players_list.group_by(&:win_value)
group_by_win_value.each do |key, value|
    @tied_players = []
    if value.count > 1
        puts "the following players are tied"
        value.each do |player|
            puts player.name``
            @tied_players << player
        end
    end
end

答案 1 :(得分:-2)

#that should do it
    highest = {"foo" => 0}
    input = { "bob" => 34, "joe" => 54, "sam" => 23, "rick" => 47}
    input.each do |key, value|
       if value > highest[value]
          highest = {key => value}
       elsif value == highest[value]
          highest.merge!(key => value)
       end
    end
    puts highest.keys
    puts highest.values