ruby使用if内部循环与用户输入

时间:2014-11-17 11:51:25

标签: ruby loops if-statement user-input

我试图通过if语句循环,如果用户输入无效,它会告诉我只输入数字或者如果为真则中断

我试过这是我的代码

class String
  def numeric?
    Float(self) != nil rescue false
  end
end
cond = false

puts "Enter number "
line = gets.chomp.strip

 while cond == false
    if (line.numeric?  )
        puts "Ok nice  "
        cond = true
        else 
        puts "Please enter number only  "

    end
 end

但如果条件为假只是打印,它会继续循环播放"请仅输入数字"

我会很高兴任何建议

谢谢

3 个答案:

答案 0 :(得分:1)

问题是,在告诉用户只输入一个号码后,你不会读取另一个号码,你只需回过头来。

解决此问题的最简单方法是将提示和输入移动到while循环,有点像这样:

class String
  def numeric?
    Float(self) != nil rescue false
  end
end
cond = false

 while cond == false
    puts "Enter number "
    line = gets.chomp.strip

    if (line.numeric?  )
        puts "Ok nice  "
        cond = true
     else 
        puts "Please enter number only  "
    end
 end

答案 1 :(得分:0)

试试这个:

 while cond == false
    if (line.numeric?  )
        puts "Ok nice  "
        cond = true
    else 
        puts "Please enter number only  "
        line = gets.chomp.strip
    end     
 end

答案 2 :(得分:0)

在重写String方法之后,试试这个:

while true                                                                                                                                                                                                             
  print "Enter number "                                                                                                                                                                                           
  line = gets.chomp.strip

  if line.numeric?
    puts "Ok nice"
    break
  else
    puts "Please enter number only"
  end                                                                                                                                                                                        
end