我要检查,如果一个字段在充满我有一个imcompleted代码:代码,如果用户输入充满
print "What is your name?"
user_input = gets.chomp.upcase
if user_input = ??
print "Nice to meet you user_input!"
else
puts "Please enter your name."
end
如何完成代码来做到这一点?
我要检查,如果一个字段在充满我有一个imcompleted代码:代码,如果用户输入充满
print "What is your name?"
user_input = gets.chomp.upcase
if user_input = ??
print "Nice to meet you user_input!"
else
puts "Please enter your name."
end
如何完成代码来做到这一点?
if user_input.blank?
puts "please enter your name"
else
puts "Nice to met you"
end
这不提供问题的答案。一旦你有足够的[声誉](https://stackoverflow.com/help/whats-reputation),你将可以[对任何帖子发表评论](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提问者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can- I-DO-代替)。 - [来自评论](/ review/low-quality-posts/16949868) – Vivz
这个问题有很多背景缺失,但有一些东西可能对您有所帮助。
基本检查,如果是零或空:
if user_input.nil? || user_input.empty?
# Ask the user to try again
end
检查,如果你指定使用正则表达式的模式匹配(见https://ruby-doc.org/core-2.1.1/Regexp.html)。例如:
if user_input =~ /^[[:upper:]][[:lower:]]+/
# One uppercase character, followed by at least one lowercase
end
第二个选项已经远远更多的可能性,但同样它取决于你的需求。
下,你想的前提:
user_input
变量(与gets.chomp
)......我们做了一些修改。
第一个是检查,使的条件确保输入不为空,第二个是如果匹配输入一定值看到。
首先,让我们先检查输入是否为空,然后再继续。我们可以用String#empty以确保字符串有至少一个字符(含空格):
print "What is your name?"
user_input = gets.chomp.upcase
# Check to make sure the input isn't empty
if !user_input.empty?
print "Nice to meet you user_input!"
else
puts "Please enter your name."
end
然后,我们可以检查,看看是否匹配输入一定的标准。不幸的是,你的问题没有明确规定什么这些标准,从而为其他用户所提出的建议,您可以使用正则表达式,看它是否与特定模式匹配,或只使用一个硬编码字符串比较:
print "What is your name?"
user_input = gets.chomp.upcase
# After making sure the input is empty, check to make sure it matches the string "Bob"
if !user_input.empty? && user.input == "Bob"
print "Nice to meet you user_input!"
else
puts "Please enter your name."
end
最后,代码中有一个错误。即使user_input
变量是另一个值,一旦用户输入验证后的输出始终为“很高兴见到你user_input”。这是因为我们没有使用正确String Interpolation:
print "What is your name?"
user_input = gets.chomp.upcase
if !user_input.empty? && user.input == "Bob"
# When using string interpolation, surround the variable you'd like to print with #{}
print "Nice to meet you #{user_input}!"
else
puts "Please enter your name."
end
正如其他用户所指出的,你应该考虑微调您的问题要求多一点。你可以在这个简单的例子中添加很多细节和实验!
“我该怎么做?” - 通过定义“填充”意味着什么,然后编写一个程序来检查user_input是否符合该定义。如果您的程序有问题,请仔细阅读您正在使用的所有方法,类,模块和库的文档,为您的程序编写测试,使用笔和纸记录执行情况,单步执行调试程序,然后在上面睡觉,从头开始,再次睡上,然后*然后只有这样*问一个关于[so]的重点狭窄的问题。此外,由于您使用[tag:performance]标记了此问题,因此您应该 –
... define,您的意思是“performance”:您是在谈论吞吐量?关于延迟?关于抖动?你在谈论冷启动,热启动还是稳态运行?你遇到的是什么典型的负载? –