Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 是否可以在多个条件while循环中以不同方式执行条件,而不创建整个新while循环?_Ruby - Fatal编程技术网

Ruby 是否可以在多个条件while循环中以不同方式执行条件,而不创建整个新while循环?

Ruby 是否可以在多个条件while循环中以不同方式执行条件,而不创建整个新while循环?,ruby,Ruby,我真的不知道怎么把这个词写得这么短,以至于我用谷歌搜索它 但是,是否可以在多个条件while循环中以不同方式执行特定条件,而不创建整个while循环。 例如,有可能做这样的事情吗 while num == "" || num == "0" #ENTER CODE 而不是这样做 while num == "" print "YOU MUST ENTER A NUMBER!" num = gets.chomp end while num == "0" print "Z

我真的不知道怎么把这个词写得这么短,以至于我用谷歌搜索它

但是,是否可以在多个条件
while
循环中以不同方式执行特定条件,而不创建整个
while
循环。


例如,有可能做这样的事情吗

while num == "" || num == "0"
   #ENTER CODE

而不是这样做

while num == ""
   print "YOU MUST ENTER A NUMBER!"
   num = gets.chomp
end

while num == "0"
   print "ZERO IS NOT A VALID NUMBER!"
   num = gets.chomp
end

我想知道有没有可能做到这一点,但要让它看起来更具视觉吸引力和简洁。

这应该可以做到,一个循环,并使用条件来打印错误消息

while num == "" || num == "0"
  print "YOU MUST ENTER A NUMBER!" if num == ""
  print "ZERO IS NOT A VALID NUMBER!" if num == "0"
  num = gets.chomp
end

你可以这样写:

while num.to_i.zero?
  case number
  when ''
    print 'YOU MUST ENTER A NUMBER!'
  when '0' 
    print 'ZERO IS NOT A VALID NUMBER!'
  end

  num = gets.chomp
end
这是可行的,因为
to_i
为字符串
“0”
nil
返回
0

此外,我建议更改错误消息以进一步简化代码:

while num.to_i.zero?
  print 'Please enter a number greater then zero'
  num = gets.chomp
end

尝试
而num==“||”0”
又短又漂亮!这就是我要找的。谢谢我没有想到使用case和when语句。我会把这个加入我的知识宝库。谢谢