基本上我正在关注Jumpstart的实验室挑战加密程序,并遇到了一些问题。
这是我的代码
class Encryptor
def cipher(rotation)
characters = (' '..'z').to_a
rotated_characters = characters.rotate(rotation)
Hash[characters.zip(rotated_characters)]
end
def encrypt_letter(letter, rotation)
cipher_for_rotation = cipher(rotation)
cipher_for_rotation[letter]
end
def encrypt(string, rotation)
letters = string.split("")
results = letters.collect do |letter|
encrypt_letter = encrypt_letter(letter, rotation)
end
results.join
end
def decrypt_letter(letter, rotation)
cipher_for_rotation = cipher(rotation)
reversed_cipher = cipher_for_rotation.to_a.reverse.to_h
reversed_cipher[letter]
end
def decrypt(string, rotation)
letters = string.split("")
results = letters.collect do |letter|
decrypt_letter = decrypt_letter(letter, rotation)
end
results.join
end
end
我的解密方法遇到了困难。以下是从irb
粘贴的以下内容2.3.0 :001 > load './encryptor.rb'
=> true
2.3.0 :002 > e = Encryptor.new
=> #<Encryptor:0x007fe93a0319b8>
2.3.0 :003 > encrypted = e.encrypt("Hello, World!", 10)
=> "Rovvy6*ay!vn+"
2.3.0 :004 > e.decrypt(encrypted, 10)
=> "\\y%%(@4k(+%x5"
正如您所看到的,在解密我的加密字符串时,它应该输出“Hello,World!”,我用它加密的内容,轮换为10.不要在这里看到我做错了什么,任何帮助将不胜感激。
答案 0 :(得分:0)
你可以只查找哈希的密钥。
def decrypt_letter(letter, rotation)
cipher_for_rotation = cipher(rotation)
cipher_for_rotation.key(letter)
end
示例:
irb(main):003:0> e = Encryptor.new
=> #<Encryptor:0x007fbcea9b65c8>
irb(main):004:0> enc = e.encrypt "Hello, World!", 10
=> "Rovvy6*ay!vn+"
irb(main):005:0> e.decrypt enc, 10
=> "Hello, World!"