How to replace the characters in a string

User9123 picture User9123 · Dec 23, 2016 · Viewed 17.1k times · Source

I have a method that I want to use to replace characters in a string:

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

My desired output for the string should be: Cohacohaa!55

However when I run this method it will not replace the characters and only outputs the string:

C
o
c
o
a
!
5
5

What am I doing wrong to where this method will not replace the correct characters inside of the string to match that in the hash and how can I fix this to get the desired output?

Answer

Aleksei Matiushkin picture Aleksei Matiushkin · Dec 23, 2016
replacements = {
  'i' => 'eye', 'e' => 'eei',
  'a' => 'aya', 'o' => 'oha'}
word = "Cocoa!55"
word.gsub(Regexp.union(replacements.keys), replacements)
#⇒ "Cohacohaaya!55"

Regexp::union, String#gsub with hash.