输入时没有输入作为有效的布尔值
我正在编写一些非常简单的代码,要求对文本输入进行确认,我想要做的是,如果用户只需按“Enter”,则将其计为“是”。 例如:
define method puts "enter some text" @text= gets.chomp puts "you entered '#{@text}', is it correct?" correct = gets.chomp if correct == 'y' || '' other_method else method end end
但是当我在Ruby上运行它时,我得到“警告,条件中的文字字符串”,无论你输入什么,都会调用“other_method”。 我找到的解决方案如下:
define method puts "enter some text" @text= gets.chomp puts "you entered '#{@text}', is it correct?" correct = gets.chomp if correct == 'y' other_method elsif correct == '' other_method else method end end
但它很烦人,我宁愿理解为什么第一个不起作用,我怎样才能使它工作? |
谢谢!
错误的含义是你在条件语句中自己提供一个字符串(文字)。 如果你这样做if correct == "y" || ""
if correct == "y" || ""
你实际上是在告诉它if correct == "y"
或""
而只是提供字符串本身并不是一个条件。
要解决此问题,您只需在操作员之后以及之前提供条件即可。 Ruby并不认为你希望在||
之后发生同样的事情 。
像这样:
define method puts "enter some text" @text= gets.chomp puts "you entered '#{@text}', is it correct?" correct = gets.chomp if correct == 'y' || correct == '' other_method else method end end
希望这可以帮助。 快乐的编码
这里的解决方案是使用Ruby非常通用的case
语句来设置你想要测试的一些“案例”:
puts "you entered '#{@text}', is it correct?" case (gets.chomp) when 'y', 'yes', '' method_a else method_b end
这可以扩展为使用正则表达式以实现更多function:
case (gets.chomp) when /\A\s*y(?:es)?\s*\z/i method_a else method_b end
现在, "y"
或"yes"
或"Yes "
都可以使用。
当你有大量的if
语句都测试同一个变量时,考虑使用case
语句来简化你的逻辑。
以下是使用Regex ( Docs )的另一种选择:
puts "enter some text" @text= gets.chomp puts "you entered '#{@text}', is it correct?" correct = gets.chomp if /^y?$/ =~ correct # This will match 'y' and empty string both other_method else method end