我发现了 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}")
来自精细手册:
小写!(*选项)→ self 或 nil
将中的字符小写;如果进行了任何更改,则返回self
,否则返回self
:nil
因此,如果没有任何需要小写的内容,
#downcase!
将返回 nil
,如文档所述。
您想使用
#downcase
而不是 #downcase!
:
animal = gets.chomp().downcase
以便
animal
得到小写的字符串。