简体   繁体   English

案例陈述不起作用

[英]Case statement don't work

I'm learning Ruby from "Programming Ruby, The Pragmatic Programmers(2nd, 2005)" and I'm stuck in the Case statement chapter. 我正在从“ Programming Ruby,The Pragmatic Programmers(2005年第2版)”中学习Ruby,并且陷入了Case语句一章。 So i copy-paste some code in my version from book: 所以我从本书中复制并粘贴了一些代码:

def kind
  puts "Type year and I'll tell you genre: "
  ask = gets.chomp

  kind = case ask
  when 1850..1889 then "Blues"
  when 1890..1909 then "Ragtime"
  when 1910..1929 then "New Orleans Jazz"
  when 1930..1939 then "Swing"
  when 1940..1950 then "Bebop"
  else "Jazz"
end


puts "You typed year #{ask}. Genre of music in that period is 
       #{kind}."
end

kind

Hence, whatever year I'm put, output is "Jazz"...What am I working incorrectly? 因此,无论我投入多少年,输出都是“爵士乐” ...我在做什么工作不正确?

gets.chomp returns a string, and you are comparing that with integers. gets.chomp返回一个字符串,您正在将其与整数进行比较。

You can inspect ask after you assigned it: 您可以检查ask你分配后:

ask = gets.chomp
p ask

When you run the script and enter a number (eg 1940), you should see "1940" printed in the terminal. 运行脚本并输入数字(例如1940)时,应该会在终端上看到"1940" The quotes around the number show you that the variable holds a string, not a number. 数字周围的引号表示变量包含字符串,而不是数字。 (FYI don't use puts here, since it won't show the quotes.) (仅供参考,此处不使用puts ,因为它不会显示报价。)

As mudasobwa wrote in his comment, the way to fix this is to cast the input to a number before you compare it: 正如mudasobwa在评论中所写,解决此问题的方法是在比较输入之前将其转换为数字:

ask = gets.chomp.to_i

If you add p ask again, you should now see that only the number is printed to the terminal, without any " surrounding it. This shows you that the variable holds an integer. 如果再次添加p ask ,现在应该看到仅数字显示在终端上,而周围没有任何" 。这表明变量包含一个整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM