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

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -