【问题标题】:how to increment ascii ord by key value如何通过键值增加ascii ord
【发布时间】:2020-01-22 21:37:01
【问题描述】:

我想通过键值递增 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

【问题讨论】:

    标签: ruby conditional-statements ascii chr ord


    【解决方案1】:

    简短的回答:因为你告诉它。

    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
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 2021-05-07
      • 1970-01-01
      • 2011-08-11
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多