如何替换字符串中的字符

Use*_*123 6 ruby string gsub

我有一个方法,我想用它来替换字符串中的字符:

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
Run Code Online (Sandbox Code Playgroud)

我想要的字符串输出应该是: Cohacohaa!55

但是,当我运行此方法时,它不会替换字符,只输出字符串:

C
o
c
o
a
!
5
5
Run Code Online (Sandbox Code Playgroud)

我在做什么错误,这个方法不会替换字符串中的正确字符以匹配中的字符,hash以及如何解决此问题以获得所需的输出?

Ale*_*kin 15

replacements = {
  'i' => 'eye', 'e' => 'eei',
  'a' => 'aya', 'o' => 'oha'}
word = "Cocoa!55"
word.gsub(Regexp.union(replacements.keys), replacements)
#? "Cohacohaaya!55"
Run Code Online (Sandbox Code Playgroud)

Regexp::union,String#gsub哈希.

  • 我对此有点困惑..? (3认同)