【问题标题】:Why does `gsub!` return `nil`?为什么`gsub!`返回`nil`?
【发布时间】:2015-06-11 12:20:59
【问题描述】:

我正在使用哈希映射按位置将字符推进:"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。这是为什么呢?

【问题讨论】:

  • 我仍然不确定为什么,但是通过更改要扫描的第二个 gsub,我能够获得预期的结果。
  • str.tr("a-z", "bcdEfghIjklmnOpqrstUvwxyzA")
  • "为什么gsub! 返回nil?" - 在文档中特别提到。

标签: ruby string gsub


【解决方案1】:

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

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

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

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

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

str = str.to_s

【讨论】:

    【解决方案2】:

    String#gsub! 在不执行替换时返回nil。

    new_str.gsub!(/[aeiou]/) {|n| n.upcase }
    

    当new_str 不包含任何元音字母时返回nil。例如,如果str 是"replace!*",new_str 是sfqmbdf!*,则没有元音。

    【讨论】:

      猜你喜欢
      • 2014-11-11
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2011-06-26
      • 2015-08-30
      相关资源
      最近更新 更多