我试图创建一个莫尔斯解码器。它用他们的摩尔斯代码替换拉丁字母。字母之间有一个空格,字之间有三个空格。
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'
有什么问题?
答案 0 :(得分:1)
问题在于:
word.gsub! letter a
它正在从右向左解释,因为letter
和a
之间没有逗号,它被视为letter(a)
函数调用。您希望将letter
和a
作为参数传递给函数调用⇒用逗号分隔 :
# ⇓ HERE
word.gsub! letter, a
BTW,gsub
可能会将哈希作为第二个参数进行替换:
word.gsub(/./, morse_dict)
会将所有字母更改为其莫尔斯代表。要处理空格,可以使用gsub
来阻止空格:
word.gsub(/./) { |l| " #{morse_dict[l]} " }.squeeze(' ')