-1

我试图创建一个莫尔斯解码器。它用摩尔斯电码代替拉丁字母。字母之间有一个空格,单词之间有三个空格。

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'

怎么了?

4

1 回答 1

1

问题在这里:

word.gsub! letter a

它是从右到左解释的,因为之间没有逗号lettera它被视为letter(a)函数调用。您希望letter和都a作为参数传递给函数调用⇒用逗号分隔它们:

#                ⇓ HERE
word.gsub! letter, a

顺便说一句,gsub可能会将哈希作为第二个参数进行替换:

word.gsub(/./, morse_dict)

会将所有字母更改为他们的莫尔斯表示。为了处理可能会使用的空格gsub,需要一个块:

word.gsub(/./) { |l| " #{morse_dict[l]} " }.squeeze(' ')
于 2016-10-18T09:10:28.610 回答