我想通过按键值递增ASCII来加密字符串。但是对于这个代码,我遇到了一个问题。
def caesar_cipher(str, key)
new_sentence = []
str.split("").each do |letter|
ascii = letter.ord
puts ascii
ascii += key if ascii >= 65 && ascii <= 90
if ascii > 90
return_start = ascii - 90
ascii = 64 + return_start
end
ascii += key if ascii >= 97 && ascii <= 122
if ascii > 122
return_start = ascii - 122
ascii = 96 + return_start
end
puts ascii
new_sentence << ascii.chr
end
puts new_sentence
end
caesar_cipher("Wh", 5)我放了一些puts来看看会发生什么,当我puts ascii的时候,我发现不要给我返回好的数字。对于'W‘,一切都很好。他从87开始,然后转到66。但我不明白为什么“h”会有问题。他从104开始,然后转到78。他为什么不去109?
发布于 2020-01-23 07:24:25
简短的回答是:因为你让它这么做。
if ascii > 90 # "h".ord == 104 so this is true
return_start = ascii - 90 # return_start is now 14
ascii = 64 + return_start # ascii is now 64 + 14 (78)
# Note this is a elaborate way of subtracting 26 from ascii
end在这样编写代码时,尝试使用p打印中间值和结果:
if ascii > 90
p return_start = ascii - 90
p ascii = 64 + return_start
endhttps://stackoverflow.com/questions/59868619
复制相似问题