【问题标题】:Code never enter any of the if statements代码从不输入任何 if 语句
【发布时间】:2011-07-10 01:19:35
【问题描述】:
begin
  selected_option = gets.chomp
  if selected_option == 1
    puts "Welcome to the Welcome Screen!"
  elsif selected_option == 2
    puts "This is the options menu."
  elsif selected_option == 3
    puts "Logging out. Goodbye!"
  else
    puts "Please select a valid option."
  end  
end while not selected_option == 3

我输入 1 或 2 或 3 并且总是收到“请输入有效选项”消息。我猜那是因为 chomp 方法将输入检索为字符串。

在选项周围使用引号可以解决这个问题吗?

【问题讨论】:

  • @Gareve:我的电脑刚刚格式化了 C 盘。谢谢。
  • @Sergio:你应该把它作为一个错误提交。
  • @Sergio Tapia,IRB 中的 IRB 或 '1 == "1"' 无法格式化硬盘。如果发生这种情况,那就完全无关了。
  • @the Tin Man:我当然是在开玩笑。
  • 我笑了。但现在我的 Mac 似乎挂起,试图格式化一些不存在的“C:”驱动器。

标签: ruby chomp


【解决方案1】:
gets.chomp.to_i

将其转换为整数。

您可能还想使用开关:

begin
  selected_option = gets.chomp.to_i
  case selected_option
    when 1
      puts "Welcome to the Welcome Screen!"
    when 2
      puts "This is the options menu."
    when 3
      puts "Logging out. Goodbye!"
    else
      puts "Please select a valid option."
  end  
end while not selected_option == 3

【讨论】:

  • 啊哈!坚硬的。让我测试一下。
  • 加上开关会更好。
猜你喜欢
  • 1970-01-01
  • 2017-10-04
  • 2020-11-28
  • 1970-01-01
  • 2016-11-09
  • 2016-10-20
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
相关资源
最近更新 更多