2016-08-24 118 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

它非常整洁,但我必须了解它是如何工作的。 但它不回答我的问题。我想知道我得到的行为的原因? –

相关问题