2016-08-24 135 views
0

我寫了一個代碼將莫爾斯碼轉換爲字符。事情是當我在終端上運行這個代碼,並通過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語法風格,但我是新的!

+4

對我的作品。我猜想,將代碼複製到在線IDE會改變某處的空白。您可以將代碼保存在在線IDE中,並向我們顯示一個重現問題的鏈接,或者更好地將您的代碼複製到在線IDE中,然後在您的計算機上重現並重現問題? –

回答

-2

此代碼可能是簡單了很多...嘗試這樣的事情(我沒有理會粘貼morse_dict全球)(PS儘量避免使用這樣的全局變量):

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 
+0

它非常整潔,但我必須瞭解它是如何工作的。 但它不回答我的問題。我想知道我得到的行爲的原因? –

相關問題