Reputation: 75
I'm learning Ruby from "Programming Ruby, The Pragmatic Programmers(2nd, 2005)" and I'm stuck in the Case statement chapter. 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?
Upvotes: 0
Views: 51
Reputation: 4364
gets.chomp
returns a string, and you are comparing that with integers.
You can inspect ask
after you assigned it:
ask = gets.chomp
p ask
When you run the script and enter a number (e.g. 1940), you should see "1940"
printed in the terminal. 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.)
As mudasobwa wrote in his comment, the way to fix this is to cast the input to a number before you compare it:
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.
Upvotes: 4