Ruby 解密方法的问题



我试图弄清楚为什么我的Ruby解密方法似乎只对字母表中的某些字母中断。

该方法的目标是获取一个输入字符串("new_str"(,并通过重写字符串中的每个字母及其在字母表中的前身来解密它。 即"BCD"应该返回"ABC"...

我可能是错的,但它似乎适用于字母 a-j,但随后对字母 k-z 进行了中断......对于最后一个集合,无论字母如何,它似乎都返回"a"b"或"z": e.g. decrypt("klmnopqrstuvwxyz"( 返回: "azazazazazbzbzbzbz">

一个观察结果是,在定义的字母变量字符串中,索引号从字母 k(索引 10(开始变为两位数......所以也许这在公式中抛出了一些东西?无论如何,任何帮助/建议表示赞赏!

def decrypt(new_str)
alphabet = "abcdefghijklmnopqrstuvwxyz"
index = 0
while index < new_str.length
new_str[index] = alphabet.index(new_str[index])
new_str[index] = alphabet[new_str[index] - 1]
index +=1
end
puts new_str
end        

你的代码应该是这样的:

def decrypt(new_str)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
index = 0
while index < new_str.length
letter_index = alphabet.index(new_str[index])
new_str[index] = alphabet[letter_index - 1]
index += 1
end
puts new_str
end
decrypt('klmnopqrstuvwxyz') #=> jklmnopqrstuvwxy
decrypt('abcdefghij')       #=> zabcdefghi
decrypt('noah')             #=> mnzg

在您的代码中,您通过在第 5 行执行new_str[index] = alphabet.index(new_str[index])来将字母切换为整数。

PS.:这是您正在实现的Caesar Cypher代码。如果您对实现它的 Ruby 方式感兴趣,请在此处查看此链接。

替换密码很容易用tr完成。

def decrypt(str)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
replacement = alphabet.split('').rotate(-1).join
str.tr(alphabet,replacement)
end
decrypt('klmnopqrstuvwxyz') #=> jklmnopqrstuvwxy
decrypt('abcdefghij')       #=> zabcdefghi
decrypt('noah')             #=> mnzg

最新更新