John Carter John Carter - 2 months ago 8
Ruby Question

Ruby - Understanding Winning Method

I have a ruby code here that has two series of hashes and there is the method.

VALID_CHOICES = {
'r' => 'rock',
'p' => 'paper',
'sc' => 'scissors',
'l' => 'lizard',
'sp' => 'spock'
}

WINNING_COMBO = {
'r' => ['sc', 'l'],
'p' => ['r', 'sp'],
'sc' => ['p', 'l'],
'l' => ['sp', 'p'],
'sp' => ['sc', 'r']
}

def win?(first, second)
WINNING_COMBO[first].include?(second)
end


Any one out there that can explain me what this win? method does? And is it similar to this?

def win?(first, second)
(first == 'sc' && second == 'p') ||
(first == 'p' && second == 'r') ||
(first == 'r' && second == 'l') ||
(first == 'l' && second == 'sp') ||
(first == 'sp' && second == 'sc') ||
(first == 'sc' && second == 'l') ||
(first == 'l' && second == 'p') ||
(first == 'p' && second == 'sp') ||
(first == 'sp' && second == 'r') ||
(first == 'r' && second == 'sc')
end


I hope I can get an explanation in layman's term or in a way a dummy can understand for that method. Sorry dummy here. I would really need your ideas. Thanks so much! Hope you understand.

Answer

This first part WINNING_COMBO[first] looks up one of the entries in WINNING_COMBO. For example if first is "r" then this would return the array ['sc', 'l']:

WINNING_COMBO['r']
#=> ["sc", "l"]

...we then check if that array contains the value of second so for the values "sc" or "l" this would be true:

WINNING_COMBO['r'].include?('sc')
#=> true

WINNING_COMBO['r'].include?('l')
#=> true

This is equivalent to the longer win? method with all the winning combinations listed out as individual conditions.