9

I've been testing this code and it's not working as I expected. Can someone shed some light on this please ?

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

, When I put in the first entry it runs, but if I use the latter entry it prints "I don't Know!"

i.e : if I enter 'js' runs, but If I enter 'JS' it throws 'I don't know!'

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Dil Azat
  • 113
  • 1
  • 1
  • 9
  • 1
    @DilAzat: Of course the corrections you received are correct, but they don't explain why you got the observed behaviour: In your original code, the first *when* expression was equivalent to `choice === ("js" || "JS")`. Now, `"js" || "JS"` evaluates to `"js"`, so you basically had `choice == "js"`, and that's why it did not work for "JS"`'. – user1934428 Dec 06 '16 at 06:42
  • Thank you for your pointers! I tried and it worked as a charm :) However, "js" || "JS" evaluates to "js", so you basically had choice == "js" <== is this because Ruby is not a very strict case sensitive language or why ? why it would think "js" is the same with "JS" ? Thanks a million in advance – Dil Azat Dec 07 '16 at 18:29
  • X||Y evaluates to X, unless it is either `nil` or `false`, in which case it evaluates to Y. In ` "js" || "JS"`, "js" is obviously neither nil nor false, so "js" is the return value of the expression. Ruby never bothers to look at the right argument. Morale of the story: Learn your operators ;-) – user1934428 Dec 08 '16 at 16:04

1 Answers1

17

Please do search before asking question, you can get its answer easily in other questions

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

After suggestions

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
Vishal G
  • 1,521
  • 11
  • 30
  • 1
    You could write `puts case choice.downcase`, then `when 'js' then "Websites!"; when "python" then....`. – Cary Swoveland Dec 06 '16 at 07:07
  • @CarySwoveland Thanks Sir! – Vishal G Dec 06 '16 at 07:16
  • If that's the case then that means, the program will alter the entry at the beginning, and by adding '.downcase' basically, I don't need to type '||' statement below, right ? I might be mistaken , but I feel like I've seen on some material someone wrote the way I posted and it worked. However, thanks to you guys, I fixed the issue I was having. Thank you :) – Dil Azat Dec 07 '16 at 18:34