小编Chr*_*s B的帖子

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

我正在使用哈希映射来按位置推进角色:"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.为什么是这样?

ruby string gsub

4
推荐指数
2
解决办法
1977
查看次数

标签 统计

gsub ×1

ruby ×1

string ×1