首页 > 解决方案 > 为什么这个 Ruby 案例块不评估为真?

问题描述

我正在学习 Ruby 的 case 语句,并认为这会起作用,但我总是在使用 else 语句。即使我将输入作为“猫”或“狗”传递,我也永远无法将输入评估为“真”。我确实验证了输入类型是“String”,所以我很困惑为什么当我输入“Cat”时,当 get 语句提示时,case 块中的“Cat”和“Cat”没有将 animal_sound 设置为“meow”

puts "Give me an animal:"
animal = gets

animal_sound = case animal
  when 'Cat' then 'meow'
  when 'Dog' then 'woof'
  else "I don't know that one, so moooo"
end

puts animal_sound

标签: ruby

解决方案


Sebastian Palma 指出\ngets添加的 导致 this 评估为假。

更改case animalcase animal.chomp解决问题。


推荐阅读