Reputation: 139
newbie here. So I was coding along on youtube and found the following error 'undefined method `+' for nil:NilClass (NoMethodError)'. I know the code works because it was able to run in the video but when I tried to run it, I received the error.
The following is my code:
def caesar_cipher(string, num)
alphabet = ("a".."z").to_a
caesar = ""
string.each_char do |letter|
if letter == " "
caesar += " "
else
old_idx = alphabet.find_index(letter)
new_idx = (old_idx + num) % alphabet.count
caesar += alphabet[new_idx]
end
end
caesar
end
puts caesar_cipher("What a string!",5)
What could be causing the error? Any help will be appreciated :)
Upvotes: 0
Views: 609
Reputation: 1714
The function only works 'a'..'z'
as @Jeremty mentioned, so W
and !
will be nil
.If you want to keep every none alphabet char, the following code maybe help.
def caesar_cipher(string, num)
alphabet = [*'a'..'z', *'A'..'Z']
caesar = ""
string.each_char do |letter|
old_idx = alphabet.find_index(letter)
if old_idx.nil?
caesar += letter
else
new_idx = (old_idx + num) % alphabet.count
caesar += alphabet[new_idx]
end
end
caesar
end
puts caesar_cipher("What a string!",5)
Upvotes: 2