简而言之,我想运行一个程序来检查用户输入是否为空,以便他重新插入所需的数据;s";在要用另一个字母替换的字符串中
print "Please enter a string: "
user_input = gets.chomp.downcase!
if user_input.empty?
print "Please enter a vaild string... "
user_input = gets.chomp.downcase!
elsif
user_input.include? "s"
user_input.gsub!(/s/, "th")
else
puts "There are no 's's in your string. #{user_input}"
end
puts "Your new thtring is #{user_input}."
问题出在这条线上
user_input = gets.chomp.downcase!
根据文件
对str的内容进行小写,如果没有进行任何更改,则返回nil。
因此,如果用户只输入小写字母的字符串,则返回nil
。
如果用户输入FOO
,那么您的函数就会正常工作。
您最好使用downcase
而不是downcase!
。downcase
总是返回字符串本身。
据我所知,您需要获得有效的用户输入(使用s
(
现在您只使用if
,这并不能保证用户输入是有效的
你可以重构成类似于的东西
puts "Please enter a string with s:"
thtring = ""
loop do
user_input = gets.chomp
next puts "Please enter some string..." if user_input.empty?
thtring = user_input.downcase
next puts "There are no 's's in your string" unless thtring.include?("s")
break thtring.gsub!(/s/, "th")
end
puts "Your new thtring is #{thtring}."