Ruby 查看用户输入是否已填充的代码
我想检查是否填写了字段。我有一个完整的代码:Ruby 查看用户输入是否已填充的代码,ruby,Ruby,我想检查是否填写了字段。我有一个完整的代码: 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 "
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
if user_input.nil? || user_input.empty?
# Ask the user to try again
end
if user_input =~ /^[[:upper:]][[:lower:]]+/
# One uppercase character, followed by at least one lowercase
end
第二种选择的可能性要大得多,但这取决于您的需要。前提是您希望:
- 打印一条信息:“你叫什么名字?”
- 让用户输入他们的名称并将其存储在
变量中(使用用户输入
)gets.chomp
- 根据输入是否符合某些条件,输出“很高兴认识您>”或“请输入您的姓名”
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
最后,代码中有一个bug。验证用户输入后,即使user\u input
变量是另一个值,输出也将始终是“很高兴见到您的用户输入”。这是因为我们没有正确使用:
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\u input
是否符合该定义。如果您的程序有问题,请仔细阅读您正在使用的所有方法、类、模块和库的文档,为您的程序编写测试,用笔和纸跟踪执行情况,在调试器中单步执行,然后休眠,从头开始,再次休眠,然后再询问,狭隘的问题。另外,由于您将这个问题标记为,您应该……定义“性能”的确切含义:您是在谈论吞吐量吗?关于延迟?关于抖动?你说的是冷启动、温启动还是稳态性能?您遇到的典型负载是什么?
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