gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:22:26 26 4
gpt4 key购买 nike

我正在使用 HashMap 按位置推进字符:“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!!!!!!!~")

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

最佳答案

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

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

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

这在某种程度上是 Ruby 中的一种模式 - 当一个方法存在多个版本时,带有 ! 的版本将修改接收器,而没有的版本将简单地返回结果。

顺便说一句,您似乎没有将 str.to_s 的结果用于任何事情。如果您知道它是一个字符串,那么 to_s 就毫无意义。如果不是,您应该使用结果,例如:

str = str.to_s

关于ruby - 为什么 `gsub!` 返回 `nil` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30780639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com