2015-03-03 44 views
0

這條線被投擲的錯誤:紅寶石錯誤 - 「+」:Fixnum對象的沒有隱式轉換成字符串(類型錯誤)

charLine.each_index { |i| charLine[i] = (charLine[i] + shift)} 

編輯:charLine[i]是一個數字(ASCII碼)和shift是一個數也

我知道它與試圖將變量中的數字添加到我在charLine數組索引中的字節ascii代碼中有關。但是我還沒有處理所有這就是爲什麼我有這個錯誤如此混亂的字符串...以下是有錯誤的方法:

 def caesarCipher(string) 
    puts "Original:\n #{string}" 
    charLine = string.chars 
    charLine.each_index { |i| charLine[i]=charLine[i].bytes } 
    charLine.flatten! 
    puts charLine.inspect 

    shift = 1 
    alphabet = ('A'..'Z').to_a 
    while shift <= alphabet.size 
     #moving up in the alphabet using ascii code 
     charLine.each_index { |i| charLine[i] = (charLine[i] + shift)} 
     #converting back to letters 
     charLine.each_index { |x| charLine[x] = charLine[x].chr } 

     puts "Shifted:\n #{charLine.inspect}" 
     puts "With a letter shift of #{shift}" 
     shift = shift + 1 
     @@shiftyArray.push(charLine.flatten) 
    end 

    end 

回答

0

我已成功地重現該問題,並與一些調試輸出,我可以看到的是,第一次迭代運行正常,問題只出現在第二次迭代( shift = 2)。

在第一次迭代燒焦線整數數組,所以整數+整數作品出細對於這一行:charLine.each_index { |i| charLine[i] = (charLine[i] + shift)}

但隨後燒焦線被轉換成陣列串的上下一循環線:

#converting back to letters 
charLine.each_index { |x| charLine[x] = charLine[x].chr } 

因此,在第二次迭代開始時,charLine現在是一個字符串數組,因爲它沒有被轉換回來。然後在.each_line上,它會嘗試將字符串+整數加起來,然後它就會爆炸。

解決方法是在每次迭代開始時將字符串數組重新映射爲整數。

charLine.map!(&:ord) 

另一種方法是不修改數組,並把結果保存到一個臨時變量,這裏是一個工作示例:

def caesar_cipher(string) 
    shiftyArray = [] 
    charLine = string.split(//) 
    charLine.map!(&:ord) 

    shift = 1 
    alphabet_size = 26 
    while shift <= alphabet_size 
    shifted_array = charLine.map { |c| (c + shift) < 122 ? (c + shift) : (c + shift) - 26 } 
    shifted_array.map!(&:chr) 
    p shifted_array 

    shift += 1 
    shiftyArray.push(shifted_array.join) 
    end 
end 

caesar_cipher("testing") 
+0

美麗!謝謝,完全解決了一切:)我需要更多地研究地圖方法 – Gcap 2015-03-03 03:07:29

1

您嘗試添加shift,這是一個Fixnum轉換爲字符串。只需撥打to_s輪班將其轉換爲字符串:

charLine.each_index { |i| charLine[i] = (charLine[i] + shift.to_s)} 
+0

不會在這種情況下工作,我需要轉移是一個整數來改變在charLine [i] – Gcap 2015-03-03 00:57:26

+0

ascii代碼它給這個錯誤,而不是'shift.to_s' 「'+':字符串不能被強制到Fixnum(TypeError)」 – Gcap 2015-03-03 00:58:17

相關問題