JeffD
JeffD

Reputation: 71

How to find elements in array that share duplicate attributes

I have an array of players. Each player has been assigned a score_value. I want to find players that tied.

The array is @@players_list, which has an unknown number of players.

I tried:

@@players_list = [player1, player2, player3]

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

This does not return an error, but also does not identify the duplicate score values

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

This returns:

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

Upvotes: 0

Views: 57

Answers (1)

JeffD
JeffD

Reputation: 71

Thanks to Sergio Tulentsev for getting me 90% there. Here's what I came up with that seems to work.

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

Upvotes: 1

Related Questions