rubyconditional-statementsasciichrord

how to increment ascii ord by key value


I want to crypt a string by incrementation of ASCII by a key value. But with this code i got a problem.

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)

I put some puts to see what happens and when I puts ascii I see that dont return me the good number. For 'W' all is fine. He start with 87and go to 66. But I dont understand why the 'h' have a problem. He start with 104 and go to 78. Why he don't go to 109 ?


Solution

  • The short answer: because you told it to.

    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
    

    When coding like this, try to print intermediate values and results using p:

    if ascii > 90
      p  return_start = ascii - 90
      p  ascii = 64 + return_start
    end