基本的高/低程序Ruby输入请求

时间:2013-06-05 00:02:39

标签: ruby

我一直试图弄清楚如何制作它,以便用户只能在这个简单的高/低猜测游戏中输入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..."

2 个答案:

答案 0 :(得分:0)

if (1..100).include?(guess) && 0 == guess % 1
  # ...
end

答案 1 :(得分:0)

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

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

正则表达式确保我们获得仅由数字(整数)组成的输入和远程检查以查看它是否在1到100之间。