我有一个方法,想用它来替换字符串中的字符:
def complexity_level_two
replacements = {
'i' => 'eye', 'e' => 'eei',
'a' => 'aya', 'o' => 'oha'}
word = "Cocoa!55"
word_arr = word.split('')
results = []
word_arr.each { |char|
if replacements[char] != nil
results.push(char.to_s.gsub!(replacements[char]))
else
results.push(char)
end
}
end
我期望的字符串输出应该是:Cohacohaaya!55
然而,当我运行这个方法时,它不会替换字符,只输出字符串:
C
o
c
o
a
!
5
5
我在做什么错误的事情,导致这个方法不能替换字符串中的正确字符以匹配
hash
中的字符?我该如何修复这个问题以获得期望的输出?
gsub(pattern, hash)
。不过你应该编辑一下关于gsub with block
的评论。 - Eric Duminil