gpt4 book ai didi

ruby - Enter with no input 作为有效的 bool 值

转载 作者:太空宇宙 更新时间:2023-11-03 17:06:26 26 4
gpt4 key购买 nike

我正在编写一些非常简单的代码,要求对文本输入进行确认,并且我想做的是,如果用户只是按“Enter”,就把它算作"is"。例如:

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" OR "" 并且只提供字符串本身不是条件。

要解决此问题,您只需在运算符之前和之后提供条件。 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 - Enter with no input 作为有效的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50116174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com