我决定做一个简单的无法取胜的摇滚,纸张,剪刀和#34;程序,它几乎完成,但有一个问题。
我希望user_input
仅在被召唤时作出回应,但无论是否"摇滚"它都会激活。输入,意思是,而不是键入"摇滚"并且该程序用"计算机播放纸张,你输了!"它回复了#34;打纸,你输了!"
played scissors, you lose!
played rock, you lose!
if #{user_input = rock}
puts "Computer played Paper, You Lose!"
这是完整的代码:
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
答案 0 :(得分:2)
这是一个无条件版本(但不会处理不正确的输入)
winning_moves = {
'rock' => 'paper',
'scissors' => 'rock',
'paper' => 'scissors',
}
puts "Computer played #{winning_moves[user_input]}, You Lose!"
答案 1 :(得分:1)
Ruby中的相等性是==
或.eql
。
=
是作业。
请将=
替换为==
中的if
。
答案 2 :(得分:1)
首先,比较时需要使用==
,并且应该将输入与字符串进行比较。您的逻辑也可以使用elsif
表示,因为无需测试输入三次,因为它只能匹配一个(或没有)值:
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
如果您想要不区分大小写的比较,可以使用casecmp
代替:
if user_input.casecmp("rock")
答案 3 :(得分:1)
或考虑case
声明。请参阅" 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
或更多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