我已经编写了一个将莫尔斯电码转换为字符的代码。问题是当我在终端上运行这段代码时,通过 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
我不明白为什么空间内(嘿(空格)裘德)被删除并附加在在线编辑器(嘿裘德(空格))的末尾。
为了进一步检查我的代码,我 Iteration #{j}
在内部 while 循环中进行了一些检查,我得到了非常奇怪的行为。我得到的输出是:
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 语法风格,但我是新手!