多个case / when条件时带||

时间:2016-12-06 06:06:07

标签: ruby switch-statement

我一直在测试这段代码,但它没有按照我的预期运行。有人可以对此有所了解吗?

language = { JS: "Websites", Python: "Science", Ruby: "Web apps" }

puts "What language would you like to know? "
choice = gets.chomp
case choice
when "js" || "JS"
  puts "Websites!"
when "Python" || "python"
  puts "Science!"
when "Ruby" || "ruby"
  puts "Web apps!"
else
  puts "I don't know!"
end

,当我输入它的第一个条目时,但是如果我使用后一个条目它会打印"我不知道!"

即:如果我输入' js'跑,但如果我进入JS'它抛出了我不知道的事情!'

1 个答案:

答案 0 :(得分:11)

请在提问之前进行搜索,您可以在其他问题中轻松获得答案

choice = gets.chomp
case choice
when 'js', 'JS'
  puts 'Websites!'
when 'Python', 'python'
  puts 'Science!'
when 'Ruby', 'ruby'
  puts 'Web apps!'
else
  puts "I don't know!"
end

建议之后

choice = gets.chomp
puts  case choice
      when 'js', 'JS'
         'Websites!'
      when 'Python', 'python'
         'Science!'
      when 'Ruby', 'ruby'
         'Web apps!'
      else
         "I don't know!"
      end