How to replace characters in a string

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 does not replace characters and only prints a string:

C
o
c
o
a
!
5
5

What am I doing wrong when this method does not replace the correct characters inside the string to match this in hash, and how can I fix this to get the desired result?

+4
source share
4 answers
replacements = {
  'i' => 'eye', 'e' => 'eei',
  'a' => 'aya', 'o' => 'oha'}
word = "Cocoa!55"
word.gsub(Regexp.union(replacements.keys), replacements)
#⇒ "Cohacohaaya!55"

Regexp::union, String#gsubwith a hash .

+13
source

Method building

Define your method with the word and subparameters:

def char_replacer word, subs
  word.chars.map { |c| subs.key?(c) ? subs[c] : c }.join
end

, if-else . String#chars Array#map Hash#key?, - . , , , - .

1

my_subs = { 'i' => 'eye', 'e' => 'eei','a' => 'aya', 'o' => 'oha' }
my_word = "Cocoa!55"

char_replacer my_word, my_subs #=> "Cohacohaaya!55"

2

my_subs = { 'a' => 'p', 'e' => 'c' }
my_word = "Cocoa!55"

char_replacer my_word, my_subs #=> "Cocop!55"
+1
replacements = { 'i' => 'eye', 'e' => 'eei', 'a' => 'aya', 'o' => 'oha' }.
  tap { |h| h.default_proc = ->(h,k) { k } }

"Cocoa!55".gsub(/./, replacements)
  #=> "Cohacohaaya!55"

. Hash # default_proc = # tap.

gsub . replacements , replacements; else (- proc), ( ).

Hash # fetch:

replacements = { 'i' => 'eye', 'e' => 'eei', 'a' => 'aya', 'o' => 'oha' }

"Cocoa!55".gsub(/./) { |s| replacements.fetch(s) { |c| c } }
  #=> "Cohacohaaya!55"

Ruby v2.2 + ( # ),

"Cocoa!55".gsub(/./) { |s| replacements.fetch(s, &:itself) }
+1
source

you can try:

my_subs = { 'i' => 'eye', 'e' => 'eei','a' => 'aya', 'o' => 'oha' }
my_word = "Cocoa!55"
my_word.split('').map{|i| my_subs[i] || i}.join

=> "Cohacohaaya! 55"

+1
source

Source: https://habr.com/ru/post/1664709/


All Articles