缩小用户输入使 gsub() 容易出错

问题描述 投票:0回答:1

我发现了 downcase() 和 gsub() 协同运行时出现的错误。只要用户输入至少包含一个大写字母,以下代码就可以正常工作。但是,当使用不包含大写字母的输入运行时,我收到错误“未定义的方法‘include?’”对于 nil:NilClass"

print("Favorite Animal: ")
animal = gets.chomp().downcase!
if animal.include?("cat")
  animal.gsub!(/cat/, "dog")
end
print("Your favorite animal: #{animal}")
ruby methods
1个回答
0
投票

来自精细手册

小写!(*选项)→ self 或 nil

self
中的字符小写;如果进行了任何更改,则返回
self
,否则返回
nil

因此,如果没有任何需要小写的内容,

#downcase!
将返回
nil
,如文档所述。

您想使用

#downcase
而不是
#downcase!
:

animal = gets.chomp().downcase

以便

animal
得到小写的字符串。

© www.soinside.com 2019 - 2024. All rights reserved.