干燥剪刀石头布 [英] DRYing up Rock Paper Scissors
问题描述
我是一个红宝石新手,尽管此代码有效,但我想知道如何改进它.我对lambda和proc之类的知识非常有限,但是任何建议都是不错的选择.有没有办法简化每种情况下的if else
语句?另外,是否有任何替代方法可以跳过case
语句,而不是将几乎整个代码都变成大的if else语句?
I'm a novice ruby programmer and although this code works, I'm wondering how I can improve it. I have very limited knowledge on lambdas and procs and the like, but any advice would be great. Is there any way to simplify the if else
statements in each case? Also, is there any alternative way to the case
statement skipped instead of making almost the entirety of the code one big if else statement?
def rps(roll)
roll_ops = ["rock", "paper", "scissors"]
pick = roll_ops.sample
result = nil
if roll == pick
result = "tie"
else
case roll
when "scissors" then
if pick == "paper"
result = "win"
else
result = "lose"
end
when "rock" then
if pick == "scissors"
result = "win"
else
result = "lose"
end
when "paper" then
if pick == "rock"
result = "win"
else
result = "lose"
end
else
puts "Please input rock paper or scissors"
end
end
puts "#{pick}, #{result}"
end
rps("scissors")
推荐答案
您可以构建一个散列,其中包含选择权以及针对该选择权丢失的选项:
You can build a hash that contains the pick and which option lose against that pick:
hash = {'scissors' => 'paper', 'rock' => 'scissors', 'paper' => 'rock'}
然后,您检查机器选择是否与您的选择相同:
Then you check if the machine pick is the same like you did:
roll_ops = ["rock", "paper", "scissors"]
pick = roll_ops.sample
if roll == pick
获胜/失败的条件变成这样:
And the win/lose condition becomes something like this:
if hash[roll] == pick
"win"
else
"lose"
end
仅需2种条件就可以清洁干净.
Nice and clean with just 2 conditions.
这篇关于干燥剪刀石头布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!