在“case ... when”语句中使用布尔运算符(Ruby)

时间:2013-09-18 01:06:44

标签: ruby boolean

我正在尝试编写一个获取用户输入并检查其有效性的方法。这是一个“案例......何时”的陈述。此部分检查用户是否仅输入了Y或N.

when 3
    input = gets.chomp.to_s.downcase
    unless input (=="y") || (=="n")
        puts "That is not a valid choice. Please enter Y or N."
        get_input(text, 3)
    end

编译器不喜欢我的布尔语句,我不知道为什么。它告诉我“语法错误,意外[x]”并指向语句的各个部分。几乎把我的头发拉到这里......我做了一件明显不对的事吗?

4 个答案:

答案 0 :(得分:4)

试试这个:

unless ['y', 'n'].include?(input)

答案 1 :(得分:2)

根据您来自的语言,您可能会发现其中一种不同的方式更具吸引力。你可以写:

 unless input (=="y") || (=="n")

如:

if !input[/^[yn]$/]
    puts "That is not a valid choice. Please enter Y or N."
    get_input(text, 3)
end

或者:

unless input[/^[yn]$/]
  ...
end  

或者:

unless (input == 'y' || input == 'n')
  ...
end

或者:

case input
when 'y', 'n'
  ...
else
  puts "That is not a valid choice. Please enter Y or N."
  get_input(text, 3)
end

答案 2 :(得分:1)

我发现unless首先读得不好。从负面开始在这里相当不错,但在更复杂的条件下它会失去可读性。

我个人更喜欢

$ if q !~ /[yn]/ # Does NOT match pattern
$   puts "That is not a valid choice. Please enter Y or N."
$   get_input(text, 3)    
$ end

让所有人都能轻松阅读。

答案 3 :(得分:0)

除了使条件正确之外,您的方法似乎还有一个递归。我怀疑你的方法是这样的:

def get_input(text, option)
  # ...
  case option
  when 1
    # ...
  when 2
    # ...
  when 3
    unless condition
      puts "That is not a valid choice. Please enter Y or N."
      get_input(text, 3) # <- recursion!
    end
  end
  # ...
end

最好在这里使用循环。像这样:

def get_input(text, option)
  # ...
  case option
  when 3
    loop do
      valid = case gets.chomp
              when /^(y|yes)$/i
                puts "positive input"
                true
              when /^(n|no)$/i
                puts "negative input"
                true
              else
                puts "That is not a valid choice. Please enter Y or N."
                false
              end
      break if valid
    end
  end
end

使用另一个case语句检查输入。如果输入有效(即yn),则返回true并退出循环break,否则返回false break没有被调用,循环重新开始。

BTW,(y|yes)匹配yyes(n|no)匹配nno^...$确保没有任何内容之前或之后,i使其不区分大小写。

因此/^(n|no)$/i匹配nNnoNonONO

相关问题