ruby - 为什么这个 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
解决方案
Sebastian Palma 指出\n
,gets
添加的 导致 this 评估为假。
更改case animal
以case animal.chomp
解决问题。
推荐阅读
- reactjs - (Redux Persist) TypeError: storage.getItem(...).then 不是函数
- c# - process.MainWindowHandle 在 Windows 服务中始终返回零
- java - 如何使用 lambda 函数创建新字符串?
- c++ - Qt4.natvis 在 Centos 7 上的 VSCode 中不起作用
- google-apps-script - 无法将视频插入稍后观看 (WL) 播放列表
- python - 如何查找哪个函数来自“从-导入”模块
- html - 如何将照片插入引导卡面板
- c++ - Argon2 malloc 访问冲突异常
- javascript - 在 html 页面中制作背景波的最佳方法是什么?
- python - 多个 DataFrame 到 Excel