没有输入时,红宝石显示#{}

时间:2016-03-06 21:41:46

标签: ruby

print"Do you want to calculate your invoice? Please enter Yes(Y) or No(N)... "
calculate_cont = ""
while calculate_cont = gets.chomp()
  calculate_cont.to_s
  calculate_cont.upcase!
  case calculate_cont
  when "Y", "YES"
      <calculations>
      print "Do you wish to continue? "
  when "N", "NO"
      puts "Thank you! Press Enter to exit!"
      gets()
      exit()
   else
     puts "Error: #{calculate_cont} is not a valid entry!
     puts "Please Enter a valid response! Yes(Y) or No(N)"
     print "Do you wish to continue? "
  end
end

当用户输入除YES或NO以外的任何其他内容时,它将使用#{calculate_cont}显示他输入的文本。如果用户只是使用#{calculate_cont}按Enter键,我如何告诉用户他输入“Nothing”?可以吗?

由于

2 个答案:

答案 0 :(得分:0)

是的,如果您正在呼叫gets.chomp且用户未输入任何值,则输出将为空字符串。只需添加另一个条件

DO SOMETHING if calculate_cont.empty?

答案 1 :(得分:0)

我创建了这个方法:

方法

 def output(calculate_cont)
    if calculate_cont == ""
      return "Nothing"
    else
      return calculate_cont
    end
 end 

使用此输出..

print"Do you want to calculate your invoice? Please enter Yes(Y) or No(N)... "
calculate_cont = ""
while calculate_cont = gets.chomp()
  calculate_cont.to_s
  calculate_cont.upcase!
  case calculate_cont
  when "Y", "YES"
      <calculations>
      print "Do you wish to continue? "
  when "N", "NO"
      puts "Thank you! Press Enter to exit!"
      gets()
      exit()
   else     
     system("cls")
     puts ""
     puts "Error: #{output(calculate_cont)} is not a valid entry!"
     puts "Please Enter a valid response! Yes(Y) or No(N)"
     print "Do you wish to continue? "
  end
end
通过这种方式,我可以向用户显示他输入的内容。 :)非常感谢