为什么`gsub!`返回`nil`?

Chr*_*s B 4 ruby string gsub

我正在使用哈希映射来按位置推进角色:"a"进入"b"等等,以及大写元音.

def LetterChanges(str)
  str.to_s
  puts str
  h = ("a".."z").to_a
  i = ("b".."z").to_a.push("a")
  hash = Hash[h.zip i]
  new_str = str.downcase.gsub(/[a-z]/,hash)
  new_str.gsub!(/[aeiou]/) {|n| n.upcase }
end

LetterChanges("hello world")
LetterChanges("sentence")
LetterChanges("replace!*")
LetterChanges("coderbyte")
LetterChanges("beautiful^")
LetterChanges("oxford")
LetterChanges("123456789ae")
LetterChanges("this long cake@&")
LetterChanges("a b c dee")
LetterChanges("a confusing /:sentence:/[ this is not!!!!!!!~")
Run Code Online (Sandbox Code Playgroud)

上面的代码按预期工作,除了示例"replace!*""123456789ae"它返回的代码nil.为什么是这样?

Jac*_*hle 9

String#gsub!修改原始字符串,如果没有执行替换,则返回该字符串或nil.

String#gsub 不会修改原始字符串,但即使没有更改,也始终返回结果.

要么new_str在方法结束时返回,要么使用gsub而不是gsub!.

这在某种程度上是Ruby中的模式 - 当存在多个版本的方法时,具有!修改接收器的那个和没有修改的那个将只返回结果.

顺便说一句,看起来你没有使用str.to_s任何结果.如果你知道它是一个字符串,那就to_s没有意义了.如果它可能不是,你应该使用结果,例如:

str = str.to_s
Run Code Online (Sandbox Code Playgroud)


Yu *_*Hao 3

String#gsub!nil当没有执行替换时返回。

new_str.gsub!(/[aeiou]/) {|n| n.upcase }
Run Code Online (Sandbox Code Playgroud)

nilnew_str不包含任何元音字母时返回。例如,如果stris "replace!*"new_stris sfqmbdf!*,则没有元音。