有人能簡單介紹一下我在這條線會發生什麼:凱撒暗號索引
new_word += alphabet[alphabet.index(i.downcase) - num]
new_word =當前new_word變量+什麼狀態呢?
這是整個方案:
def cipher(word, num)
alphabet = ('a'..'z').to_a.concat(('A'..'Z').to_a)
new_word = ""
word.each_char do |i|
if !alphabet.include?(i)
new_word +=i
else
new_word += alphabet[alphabet.index(i.downcase) - num]
end
end
return new_word.downcase.capitalize
end
puts cipher("Apples? and Oranges!", 2)
這裏有基本上爲此構建的String#tr方法。無需轉換爲unicode或其他。我使用#tr構建了一個密碼。讓我知道你是否想看看我做了什麼。你會發現它更高效和可靠。 – Charles