1

我一直在试图弄清楚如何做到这一点,以便用户只能为这个简单的高/低猜谜游戏输入 1 到 100 之间的正整数。我想要它,所以除了 1 到 100 之间的整数之外的任何东西都会通知用户他们不能对所有输入都这样做。有没有一种简单的方法可以做到这一点?

我现在拥有的:

count=0
play = true
while play == true

print "Give me a random number between 1 and 100: "
    max= gets.to_i
    num= rand(max)
puts "Now guess between 1 and " + max.to_s + 
"."
print "What is your guess?: "
    guess=gets.to_i

    while guess != num && play != false 
        if guess > num
         print "Too high! "
            guess=gets.to_i
            count+=1
    elsif guess < num
        print "Too low! "
            guess=gets.to_i
             count+=1
        else
            break
        end
end

puts "Good Job! You figured it out in " + count.to_s + " attempts!"
print "Want to try again? y/n "

answer=gets.chomp!
    if answer  == 'n'
        play = false
        break
    end

if 
    answer == 'y'
    play = true
end 


end
puts "Maybe next time..."
4

2 回答 2

0
if (1..100).include?(guess) && 0 == guess % 1
  # ...
end
于 2013-06-05T00:22:17.460 回答
0

最简单的方法是使用正则表达式和范围。

guess = gets.chomp
if(guess =~ /\A\d+\Z/ && (1..100) === guess.to_i)
  #do stuff
else
  puts "Please enter a valid number"
end

正则表达式确保我们得到一个仅由数字(一个整数)组成的输入,并且 ranged 检查它是否在 1 到 100 之间。

于 2013-06-05T01:27:14.283 回答