0

I got to solve the problem I was trying to solve, but the thing is that I am not sure why it worked, I just started adding methods.

So if anyone could explain why worked:

def replace(string1, letter_a, letter_b)
  
  replacements = {letter_a => letter_b}

#this is the part I am not sure why is working:
   
initial_string.split('').map{|i| replacements[i] || i}.join
    end
Esteban
  • 7
  • 4

1 Answers1

1

Firstly I recommend to use built-in methods String#gsub or String#tr

string.gsub(%r{#{replaceable_letter}}, replacing_letter)

"abcdef".gsub(/a/, "b") # => "bbcdef"
string.tr(replaceable_letter, replacing_letter)

"abcdef".tr("a", "b") # => "bbcdef"

Instead of initial_string.split('').map you can use initial_string.each_char.map


Explanation of your code:

replacements = {letter_a => letter_b}

is hash where replaceable letter is key and replacing letter is value

For example { "a" => "b" }

Than you split your string to chars array

After that map over this array

For every char you check the hash, for example:

replacements["a"] # => "b"
replacements["c"] # => nil

If hash has such key, you take replacing letter, if not take origin letter. Compare and read about || operator:

nil || "f" # => "f"
"b" || "a" # => "b"

And finally join new array

mechnicov
  • 12,025
  • 4
  • 33
  • 56