Ruby - How do I shorten my method -
i have hash here:
valid_choices = { 'r' => 'rock', 'p' => 'paper', 'sc' => 'scissors', 'l' => 'lizard', 'sp' => 'spock' }
and method compares here:
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
how can rewrite method in short concise code means same thing? idea? possible using hashes?
you should define clear rules each token can win:
wins = { 'r' => %w{l sc}, 'p' => %w{r sp}, 'sc' => %w{p l}, 'l' => %w{p sp}, 'sp' => %w{r sc} }
now can determine wins using simple lookup:
def win?(first, second) wins[first].include?(second) end
while there may several 'clever' ways avoid explicit structure wins
, explicit rules more understandable - , therefore, more maintainable. conciseness in code considered positive attribute improves readability of code. conciseness extreme causes code difficult understand not strive for.
Comments
Post a Comment