【发布时间】: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?" - 在文档中特别提到。