我写了一个代码将莫尔斯码转换为字符。事情是当我在终端上运行这个代码,并通过IRB,我得到预期的输出,但是当我在线IDE上运行相同的代码时,我得到不同的输出。相同Ruby代码的不同输出?
代码:
$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
输出I在控制台和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语法风格,但我是新的!
对我的作品。我猜想,将代码复制到在线IDE会改变某处的空白。您可以将代码保存在在线IDE中,并向我们显示一个重现问题的链接,或者更好地将您的代码复制到在线IDE中,然后在您的计算机上重现并重现问题? –