如何使用.include?捕获导致相同操作的多个选项

时间:2019-05-18 14:00:37

标签: ruby

我正在编写一个简单的计算器,询问用户要在“ +”,“-”,“ *”和“ /”之间进行选择,要执行什么计算。

当我用||分隔每个选项时,代码起作用。但是,我更喜欢使用.include?避免重复。

while play_again != "N"
  puts "Enter a first number:"
  first_num = gets.chomp.to_i
  puts "Enter a second number:"
  second_num = gets.chomp.to_i
  puts "Which operation would you like to perform? '+', '-', 'x', '/'"
  operator = gets.chomp
  if operator == "+" || operator == "-" || operator == "x" || operator   
  == "/"
    puts calculator(first_num, second_num, operator)
  else
    puts "That wasn't a valid selection."
  end
  puts "Do you want to calculate something else? (Y/N)"
  play_again = gets.chomp
end

我试图用if operator改写以if operator.include?(%w[+ - X /].to_s)开头的行,但这不能正确捕获用户输入,并始终显示“那不是有效的选择。”

2 个答案:

答案 0 :(得分:3)

通过这种方式

if %w(+ - * /).include?(operator)

一种更简单的方法

if ["+", "-", "*", "/"].include?(operator)

这很有意义,你不觉得吗?您正在检查操作员是否包含在某些选项中。在这种情况下,选项是四个字符串,四个基本数学运算的符号。

答案 1 :(得分:1)

case when控件结构使您可以指定多个条件。听起来很难,实际上很容易:

puts case operator
  when  '+', '-', 'x', '/' then calculator(first_num, second_num, operator)
  else "That wasn't a valid selection."
end