I have this question. Using the Ruby language, have the function CaesarCipher(str,num) take the str parameter and perform a Caesar Cipher shift on it using the num parameter as the shifting number. A Caesar Cipher works by shifting each letter in the string N places down in the alphabet (in this case N will be num). Punctuation, spaces, and capitalization should remain intact. For example if the string is "Caesar Cipher" and num is 2 the output should be "Ecguct Ekrjgt".
Any my code looks like this. I think the onlt problem i have is to update each letter and then each word within the loops. please help. thank you
def Caesar_cipher(str, num)
if num > 25
num -= 26
end
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
str = str.split(" ")
str.each do |word|
word.each_char do |c|
if alphabet.include?(c)
n = alphabet.index(c) + num
if n > 25
n -= 26
end
c = alphabet[n]
end
end
end
return str
end
puts Caesar_cipher("zabcd", 1) // "zabcd"
c = alphabet[n]doesn't update the character, it just assigns to a local variablecthat is never used.strso can't expect it would contain the result.Enumerator#each*family methods return containing object, no block results. You may look forEnumerable#collect(#map) methods. Also condition to keepnin 0-25 boundary can be simply rewritten with modulo, liken %= 26.cin this case), use ofeach_char(could be chained likeeach_char.collect ... .joinfor gathering results). Shall I report my findings in more depth, or you'll figure this on your own?