我编写了一个代码,用于将莫尔斯代码转换为字符。问题是当我在终端上运行此代码时,通过IRB,我得到了预期的输出,但是当我在在线IDE上运行相同的代码时,我获得了不同的输出。
代码:
$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" => "-----"
}
def decodeMorse(morseCode)
words = morseCode.split(' ')
i=0
sentence = []
while i < words.length
word = words[i].split(' ')
j = 0
while j < word.length
sentence.push($morse_dict.key(word[j]))
if word.length - j == 1
sentence.push(' ')
end
j += 1
end
i += 1
end
sentence = sentence.join().upcase
return sentence
end
sentence= decodeMorse('.... . -.-- .--- ..- -.. .')
puts sentence
输入我进入控制台和IRB:HEY JUDE
输入我在线编辑:HEYJUDE
我不明白为什么空间(HEY(空间)JUDE)被删除,并在网上编辑器(HEYJUDE(空格))的末尾附加。
为了进一步检查我的代码,我在内部while循环中放了一些检查作为 Iteration #{j}
,我得到了非常奇怪的行为。我得到的输出是:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7
而不是
Iteration 1
Iteration 2
Iteration 3
Iteration 1
Iteration 2
Iteration 3
Iteration 4
为什么会这样? 我已尽力遵循ruby语法风格,但我是新手!
答案 0 :(得分:-2)
这段代码可能更简单......尝试这样的事情(我没有打扰粘贴morse_dict
全局)(p.s.尽量避免使用像这样的全局变量):
def decode_morse(morse_code)
morse_dict = { ... } # placeholder, use your actual map here
out = []
morse_code.split(' ').each do |w|
w.split(' ').each do |l|
out.push morse_dict.invert[l] # actual letter
end
out.push ' ' # after each word
end
out.join.strip # final output
end