我寫了一個代碼將莫爾斯碼轉換爲字符。事情是當我在終端上運行這個代碼,並通過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中,然後在您的計算機上重現並重現問題? –