Ethem GÜR Ethem GÜR - 1 month ago 7
Ruby Question

Ruby Morse Decoder

I tried to create a Morse Decoder. It replaces latin letters with their morse codes. There is one whitespace between letters and three whitespace between words.

def decodeMorse(morseCode)
morse_dict = {
"a" => ".-","b" => "-...","c" => "-.-.","d" => "-..","e" => ".","f" => "..-.","g" => "--.","h" => "....","i" => "..","j" => ".---","k" => "-.-","l" => ".-..","m" => "--","n" => "-.","o" => "---","p" => ".--.","q" => "--.-","r" => ".-.","s" => "...","t" => "-","u" => "..-","v" => "...-","w" => ".--","x" => "-..-","y" => "-.--","z" => "--.."," " => " ","1" => ".----","2" => "..---","3" => "...--","4" => "....-","5" => ".....","6" => "-....","7" => "--...","8" => "---..","9" => "----.","0" => "-----"
}

wordList = morseCode.split(" ")

wordList.each do |word|
word = word.downcase
word.split("").each do |letter|
a = ' ' + morse_dict[letter].to_s + ' '
word.gsub! letter a
end
end

sentence = wordList.join(' ')

return sentence.lstrip

end

puts decodeMorse("Example from description")


Then I got this error:

NoMethodError: undefined method `letter' for main:Object
from codewars.rb:12:in `block (2 levels) in decodeMorse'
from codewars.rb:10:in `each'
from codewars.rb:10:in `block in decodeMorse'
from codewars.rb:8:in `each'
from codewars.rb:8:in `decodeMorse'


What is wrong?

Answer

The problem is here:

word.gsub! letter a

it is being interpreted from the right to the left since there is no comma between letter and a it’s being treated as letter(a) function call. You want both letter and a to be passed as parameters to a function call ⇒ separate them with comma:

#                ⇓ HERE
word.gsub! letter, a

BTW, gsub might take a hash as a second param to make substitutions:

word.gsub(/./, morse_dict)

would change all letters to their Morse representations. To deal with spaces one might use gsub that takes a block:

word.gsub(/./) { |l| " #{morse_dict[l]} " }.squeeze(' ')
Comments