Search code examples
rubycaesar-cipher

Caesar cypher indexing


Can someone briefly explain me what happens in this line:

new_word += alphabet[alphabet.index(i.downcase) - num]

new_word = current state of new_word variable + what?

This is whole program:

def cipher(word, num)
alphabet = ('a'..'z').to_a.concat(('A'..'Z').to_a)
new_word = ""

word.each_char do |i|
  if !alphabet.include?(i)
    new_word +=i
  else
    new_word += alphabet[alphabet.index(i.downcase) - num]  
  end
end

return new_word.downcase.capitalize
end

puts cipher("Apples? and Oranges!", 2)

Solution

  • new_word is a String, so the value on the right will be appended to it. The expression alphabet[alphabet.index(i.downcase) - num] is just an inefficient way of determining a character that is shifted num places in the alphabet.

    alphabet is an Array containing the character values corresponding to the letters of the alphabet, starting with lowercase letters and then followed by uppercase letters.

    The index method in this case finds the index of the first occurence of the character value i in alphabet. This index is then decreased by num. The character corresponding to this new position is finally looked up in alphabet, and the result is appended to new_word.

    Note also that the result will „wrap around“ in the sense that if the new index is negative, the array will be indexed from the back, resulting in the capital letters if num is not too large. Those potential uppercase letters will be downcased in new_word.downcase.capitalize.


    The downcase part is strange, because it means that the „cipher“ is not invertible. Note also that this will not work as you might expect if nums absolute value is so large that the lookup is out of bounds.