You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么这段Ruby的case代码块无法正确匹配输入的Cat、Dog值?

问题根因

Ruby的gets方法在捕获用户输入时,会自动将输入完成后按下回车生成的换行符\n追加到返回字符串的末尾。你输入Cat时,animal变量的实际值为"Cat\n",和case分支中写死的"Cat"字符串内容不一致,因此无法触发对应匹配分支,最终只会走到else逻辑。

修复方案

只需要在gets后调用chomp方法,该方法会专门移除字符串末尾的换行符,就能保证输入内容和分支条件正常匹配。

修正后可运行代码

puts "Give me an animal:" 
animal = gets.chomp

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

可选优化

如果需要兼容大小写输入(比如用户输入cat/CAT也能匹配成功),可以再追加downcase方法统一转小写,对应调整分支条件即可:

animal = gets.chomp.downcase
# 对应分支修改为小写匹配
when 'cat' then 'meow'
when 'dog' then 'woof'

内容的提问来源于stack exchange,提问作者Jack Collins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 04:45:10