使用downcase!与gsub!时全小写输入触发NilClass错误,求助排查
问题分析与解决办法
问题根源
Ruby 里的 downcase! 是原地修改字符串的方法:
- 如果字符串包含大写字母,它会把字符串转成小写并返回修改后的字符串;
- 如果字符串已经是全小写,没有任何修改发生,它会返回
nil。
你的代码里直接把 downcase! 的返回值赋值给 animal,当输入全小写时,animal 就变成了 nil,后续调用 animal.include?("cat") 自然会触发 undefined method include?' for nil:NilClass` 错误。
解决方案
有两种简单的修复方式:
方案1:使用不带感叹号的 downcase 方法
downcase 会返回一个新的小写字符串,无论原字符串是否需要修改,都不会返回 nil:
print("Favorite Animal: ") animal = gets.chomp().downcase if animal.include?("cat") animal.gsub!(/cat/, "dog") end print("Your favorite animal: #{animal}")
方案2:单独调用 downcase!,不直接赋值返回值
如果一定要用原地修改的方法,把 downcase! 和赋值分开,这样即使它返回 nil,animal 仍然指向原来的字符串对象:
print("Favorite Animal: ") animal = gets.chomp() animal.downcase! if animal.include?("cat") animal.gsub!(/cat/, "dog") end print("Your favorite animal: #{animal}")
内容的提问来源于stack exchange,提问作者K Man
相关产品推荐
相关产品推荐

