我试图创建一个莫尔斯解码器。它用摩尔斯电码代替拉丁字母。字母之间有一个空格,单词之间有三个空格。
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")
然后我得到了这个错误:
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'
怎么了?