简体   繁体   中英

Ruby skips if statements

I have a ruby program here w/c consists of hashes. Basically when the user enters l or p or sc it will check if the computer generated key matches the criteria on the first variable w/c is the player or the user. If it matches the criteria it will return you won. But if it's not it will return you loose. otherwise if it's the same it will print a tie.

MY_CHOICES = { 
 'l' => 'light',
 'p' => 'paper', 
 'sc' => 'scan',
}

def test?(first, second)
  (first == 'p' && second == MY_CHOICES ['l']) ||
  (first == 'l' && second == MY_CHOICES ['p']) ||
  (first == 'sc' && second == MY_CHOICES ['sc']) ||
  (first == 'l' && second == MY_CHOICES ['l'])
end 

def print_results(player, computer)
  if test?(player, computer)
    puts("You won!")
  elsif test?(computer, player)
    puts("Computer won! You loose!")
  else
    puts("It's a tie!")
  end
end

puts "Enter a key: "
choice = gets().chomp()
computer_choice = MY_CHOICES.values.sample
print_results(choice, computer_choice)
puts("You chose: #{choice}, computer choose: #{computer_choice}"

With the codes above, my code is skipping the codes and always prints "It's a tie" I don't what I am missing here. Any idea?

You're getting the user's input and testing it against 'rock', 'paper' and 'scissors', however you've stated that the user is entering 'l', 'p', and 'sc' so test will never evaluate to true

As an example, saving this as rps.rb and running:

> ruby rps.rb 
Enter a key: 
rock
You won!
You chose: rock, computer choose: light

Have you tried fixing your code a bit:

def test?(player, computer)
  (player== 'rock' && computer== VALID_CHOICES['sc']) ||
  (player== 'paper' && computer== VALID_CHOICES['r']) ||
  (player== 'scissors' && computer== VALID_CHOICES['sc']) ||
  (player== 'paper' && computer== VALID_CHOICES['sp'])
end 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM