问题
I'm trying to figure out why my Ruby decryption method seems to break only for certain letters of the alphabet.
The goal of the method is to take an input string ("new_str") and decrypts it by rewriting EACH letter in the string with its predecessor in the alphabet. i.e. "bcd" should return "abc" ...
I could be wrong but it seems to work for the letters a-j, but then breaks for the letters k-z... for that last set it seems to return either an "a" "b" or "z" no matter the letter: e.g. decrypt("klmnopqrstuvwxyz") returns: "azazazazazbzbzbz"
One observation is that in the defined alphabet variable string, the index numbers become double digits starting at the letter k (index 10)... so maybe that's throwing something off in the formula? Anyway, any help / suggestions appreciated!
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
回答1:
Your code should be like:
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
In your code, you were switching a letter by an integer number by doing new_str[index] = alphabet.index(new_str[index])
in the 5th line.
PS.: This is a Caesar Cypher code you are implementing. If you are interested in a more Ruby way to implement it, check this link here.
回答2:
Substitution ciphers are easily accomplished with 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
来源:https://stackoverflow.com/questions/45645170/issue-with-ruby-decryption-method