I'm just looking for any tips to improve the code, particularly easier ways to change the main logic of the code so that it's shorter.

puts "Let's play rock, paper, scissors"

compScore = 0
humanScore = 0

until compScore == 5 || humanScore == 5

    puts "Select your weapon. Rock, paper or scissors?"

    human = gets.chomp.downcase
    comp = ["rock", "paper", "scissors"].sample

    #human wins
    if (human == "rock" && comp == "scissors") || (human == "scissors" && comp == "paper") || (human == "paper" && comp == "rock")
        p "You won!"
        humanScore += 1

    elsif (human == "rock" && comp == "rock") || (human == "paper" && comp == "paper") || (human == "scissors" && comp == "scissors")
        p "Draw! No point awarded"

    #computer wins
    else compScore += 1
        p "You lose."   

    #Resulted Scores
    p "Human Score: #{humanScore}"
    p "Computer Score: #{compScore}"

    #Resulted Choices
    p "Human chose: #{human}"
    p "Computer chose: #{comp}"
    #Tell who wins
    p humanScore > compScore ? ("YOU WIN!") : ("COMPUTER WINS!.")
| improve this question | | | | |
  • 1
    \$\begingroup\$ Please use the normal formatting option for the code. Ruby is not a language that can use the snippet feature. \$\endgroup\$ – Marc-Andre Nov 7 '17 at 1:18

Fix your formatting. While the computer doesn't care about indentation, humans do. And code is read (by humans) many more times than it's written. And this code is hard to read.

The whole "draws" logic can be replaced with a simple check: human == comp.

Determining the winner of a "hand" in rock-paper-scissors can be done in many, many, many ways. You're checking it "manually" in a sense, by writing out all the possible combinations. But you could also assign numeric values to the choices (for instance, their index in an array), and compare those numbers instead. Or so something like this, where the player's choice is used to determine what the winning response would be and see if the computer picked that:

choices = %w(rock paper scissors).reverse

index = choices.index(player_choice)
winning_choice = choices[index - 1] 

if computer_choice == winning_choice
  # computer wins
  # human wins

(this assumes that player_choice and computer_choice have already been set and that you've checked for draws.)

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.