0

I decided I would make a simple unwinnable "rock, paper, scissors" program and it is almost complete, however there is a issue.

I want the user_input to only respond when called upon, however it activates regardless of if "rock" was input, meaning, instead of typing "rock" and the program responding with "Computer played paper, you lose!" it responds with "played paper, you lose!"

 played scissors, you lose!
 played rock, you lose!

if #{user_input = rock}
  puts "Computer played Paper, You Lose!"

This is the full code:

print "Rock, Paper or Scissors?\n"
user_input = gets.chomp
puts "You played #{user_input}!"
if #{user_input = rock}
  puts "Computer played Paper, You Lose!"
end

if #{user_input = paper}
  puts "Computer played scissors, You Lose!"   #code
end

if #{user_input = scissors}
  puts "Computer played rock, You Lose!"
end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Boris
  • 75
  • 8

4 Answers4

2

Here's a conditional-free version (doesn't handle incorrect input, though)

winning_moves = {
  'rock' => 'paper',
  'scissors' => 'rock',
  'paper' => 'scissors',
}

puts "Computer played #{winning_moves[user_input]}, You Lose!"
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

The equality in Ruby is == or .eql.

= is assignment.

Please replace the = with == in your ifs.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
473183469
  • 243
  • 3
  • 10
1

First, you need to use == when you compare, and you should be comparing the input with a string. Also your logic could be expressed using elsif as there is no need to test the input three times as it can only match one (or no) value:

if user_input == "rock"
    puts "Computer played Paper, You Lose!"
elsif user_input == "paper"
    puts "Computer played scissors, You Lose!"
elsif user_input == "scissors"
    puts "Computer played rock, You Lose!"
else
    puts "Invalid input"
end  

If you want case-insensitive comparison you can use casecmp instead like this:

if user_input.casecmp("rock")
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
jpw
  • 44,361
  • 6
  • 66
  • 86
1

Or consider a case statement. See "How to write a switch statement in Ruby"

case user_input
when "rock"
  puts "Computer played Paper, You Lose!"
when "paper"
  puts "Computer played scissors, You Lose!"
when "scissors"
  puts "Computer played rock, You Lose!"
else
  puts "Invalid input"
end

Or more DRYly:

computer_plays = case user_input
                   when "rock"
                     "paper"
                  when "paper"
                     "scissors"
                  when "scissors"
                     "rock"
                  end
puts "Computer played #{computer_plays}, You Lose!" if computer_plays
Community
  • 1
  • 1
Greg
  • 2,549
  • 2
  • 24
  • 30
  • True - given the OP's experience level I just wanted to introduce a different concept - forgot to past the link I was going to though – Greg Oct 29 '15 at 11:44