`gets.chomp.downcase!`得到一个空字符串错误

时间:2015-11-08 08:08:08

标签: ruby string

如果我这样做

user_input = gets.chomp
user_input.downcase!

我可以输入一个没有错误的字符串 但是,如果我这样做

user_input = gets.chomp.downcase!

我的user_input字符串未填充,并且对字符串的任何后续工作都会返回错误,指出我的字符串为空。为什么会这样?

1 个答案:

答案 0 :(得分:3)

如果没有进行任何更改,

String#downcase!会返回nil

'hello'.downcase!
# => nil
'hello'.downcase
# => "hello"

因此,如果输入的字符串没有大写字母,gets.chomp.downcase!将返回nil