密码学中有一个凯撒密码。我正在尝试用Ruby构建一个,但是我不知道如何在范围('a'..'z').to_a.join中使用大写字母。如何使用大写字母?
class Caesar
def initialize(shift)
alphabet = ('a'..'z').to_a.join
i = shift % alphabet.size
@decrypt = alphabet
@encrypt = alphabet[i..-1] + alphabet[0...i]
end
def encrypt(string)
string.tr(@decrypt, @encrypt)
end
def decrypt(string)
string.tr(@encrypt, @decrypt)
end
end
cipher_1 = Caesar.new(1)
s = 'A man, a plan, a canal: Panama!'
puts s
s_encoded = cipher_1.encrypt(s)
puts s_encoded
pudaats = cipher_1.decrypt(s_encoded)
puts pudaatsOUTput
一个人,一个计划,一个运河:巴拿马! qmbo,b qmbo,b dbobm: Pbobnb! 一个人,一个计划,一个运河:巴拿马!
但我需要放出去
一个人,一个计划,一个运河:巴拿马! qmbo,b qmbo,b dbobm: Qbobnb! 一个人,一个计划,一个运河:巴拿马!
发布于 2014-10-11 00:26:29
LOWER_CASE = ('a'.ord .. 'z'.ord)
UPPER_CASE = ('A'.ord .. 'Z'.ord)
def shift(c, by)
byte = c.ord
if LOWER_CASE.include?(byte) then
((((byte - LOWER_CASE.min) + by) % 26) + LOWER_CASE.min).chr
elsif UPPER_CASE.include?(byte) then
((((byte - UPPER_CASE.min) + by) % 26) + UPPER_CASE.min).chr
else
c
end发布于 2014-09-28 23:57:41
这里的问题就在你定义的字母表中。
a..z # ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]注意这里没有大写字母。唯一正在转换的字母是小写字母。因此,您还需要更改范围以包括大写字符:
alphabet = (("A".."Z").to_a + ("a".."z").to_a).join然后你就会得到正确的结果。
https://stackoverflow.com/questions/26090739
复制相似问题