rubycaesar-cipher

My Caesar Cipher code is failing when I pass in a string containing uppercase characters


I wrote a Caesar Cipher encryption program in Ruby. It seemingly worked just fine when I passed in strings containing lowercase characters until I passed in a string that had an uppercase character. The code is raising a NoMethodError in between the lines of main.rb:7:in block in `caeser_cipher': undefined method `+' for nil (NoMethodError) whenever I pass in a string that has uppercase characters.

Here's my code:

def caeser_cipher(string, key)
  alphabet = ('a'..'z').to_a
  cipher = ""

  string.each_char do |char|
    if alphabet.include?(char.downcase) 
      new_key = (alphabet.index(char) + key) % 26
      char = alphabet[new_key]
    end 
    cipher << char
  end
  cipher
end

puts "Enter whatever you please (of course a string of text) that you want encrypted!!!"
text = gets.chomp
puts "And then the offset value"
num = gets.chomp.to_i

puts caeser_cipher(text, num)

I tried wrapping char = alphabet[new_key] in another if condition to check for char == char.upcase and if that evaluated to true, to do this char = alphabet[new_key].upcase which also failed.


Solution

  • The problem is on line

    new_key = (alphabet.index(char) + key) % 26
    

    If the char is not an lowercase character, it will not be found in the alphabet, so index will return nil.

    You need to look up the lowercased version of the char, so maybe change the line to

    new_key = (alphabet.index(char.downcase) + key) % 26