-4
好的,我正在學習ruby並創建了caeser密碼。當我看到其他人的解決方案後,他們是不同的,然後我提出了。我在挑選他們的解決方案的工作方式時遇到了一些麻煩。它絕對看起來像是我創建的更高效/優雅的解決方案。Caeser密碼紅寶石
def caesar_cipher(string, shift = 1)
alphabet = Array('a'..'z')
non_caps = Hash[alphabet.zip(alphabet.rotate(shift))]
# I understand this is making an a-z array, then making a hash with the key being the original and value being the shifted letter ie. with a shift of 3, "a" => "d"
alphabet = Array('A'..'Z')
caps = Hash[alphabet.zip(alphabet.rotate(shift))]
encrypter = non_caps.merge(caps) #I think that this just combines the two hashes together?
string.chars.map { |c| encrypter.fetch(c, c) }
#This is the part i really just do not fully understand. You split the string up into characters, then iterate through each one, then does fetch just replace the letter with the the correlated values in the hash?
end
p caesar_cipher("testingzZ1Z").join
我只是想確保我正確認識這一點,並希望聽到的話,就有可能創造這樣的密碼的更好的方法。
歡迎來到堆棧溢出,你是對的。看到http://ruby-doc.org/core-2.2.0/Hash.html#method-i-fetch,現在出去! :) –
歡迎來到堆棧溢出。通過編寫一些測試代碼並使用調試'puts'語句,使用調試器或像RubyMarkers這樣的vim或Sublime Text插件,您的問題可以很容易地得到解答。請閱讀「[問]」和「[mcve]」和http://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users。至於更好的方法,這是對你的進一步研究。 –
http://meta.stackoverflow.com/questions/253894/how-to-handle-explain-how-this-code-dump-works-questions/253896#comment17104_253896 –