2016-01-20 56 views
-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 

我只是想确保我正确认识这一点,并希望听到的话,就有可能创造这样的密码的更好的方法。

+1

欢迎来到堆栈溢出,你是对的。看到http://ruby-doc.org/core-2.2.0/Hash.html#method-i-fetch,现在出去! :) –

+1

欢迎来到堆栈溢出。通过编写一些测试代码并使用调试'puts'语句,使用调试器或像RubyMarkers这样的vim或Sublime Text插件,您的问题可以很容易地得到解答。请阅读“[问]”和“[mcve]”和http://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users。至于更好的方法,这是对你的进一步研究。 –

+0

http://meta.stackoverflow.com/questions/253894/how-to-handle-explain-how-this-code-dump-works-questions/253896#comment17104_253896 –

回答

1

您应该尝试更频繁地查看Ruby文档。

是的,Hash#merge将两个哈希结合在一起。

Hash#fetch将尝试在哈希中获取值,如果找不到,可以提供默认值。

所以encrypter会替换它可以加密的所有字符。如果它不能加密它,因为它不在散列中,它会让它一个个留下。

+0

谢谢你的输入! – jslice