Ruby 莫尔斯解码器
Ruby Morse Decoder
我试图创建一个莫尔斯解码器。它用莫尔斯电码代替了拉丁字母。字母之间有一个空格,单词之间有三个空格。
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'
怎么了?
问题出在这里:
word.gsub! letter a
它被从右到左解释,因为 letter
和 a
之间没有逗号,它被视为 letter(a)
函数调用。您希望将 letter
和 a
作为参数传递给函数调用⇒ 用逗号 分隔它们 :
# ⇓ HERE
word.gsub! letter, a
顺便说一句,gsub
可能会将散列作为第二个参数来进行替换:
word.gsub(/./, morse_dict)
会将所有字母更改为其摩尔斯表示法。要处理空格,可以使用 gsub
占用一个块:
word.gsub(/./) { |l| " #{morse_dict[l]} " }.squeeze(' ')
我试图创建一个莫尔斯解码器。它用莫尔斯电码代替了拉丁字母。字母之间有一个空格,单词之间有三个空格。
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'
怎么了?
问题出在这里:
word.gsub! letter a
它被从右到左解释,因为 letter
和 a
之间没有逗号,它被视为 letter(a)
函数调用。您希望将 letter
和 a
作为参数传递给函数调用⇒ 用逗号 分隔它们 :
# ⇓ HERE
word.gsub! letter, a
顺便说一句,gsub
可能会将散列作为第二个参数来进行替换:
word.gsub(/./, morse_dict)
会将所有字母更改为其摩尔斯表示法。要处理空格,可以使用 gsub
占用一个块:
word.gsub(/./) { |l| " #{morse_dict[l]} " }.squeeze(' ')