Skip to content

Instantly share code, notes, and snippets.

@violetguos
Created June 4, 2020 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save violetguos/1a9bf6a921ac43160e208878d9cfda30 to your computer and use it in GitHub Desktop.
Save violetguos/1a9bf6a921ac43160e208878d9cfda30 to your computer and use it in GitHub Desktop.
TOP's ruby project
def caesar_cipher(msg, offset)
msg_arr = []
msg.chars.each do |m_char|
if m_char.match(/[A-Z]/)
# wraps around 26 alphabets, mod 26
msg_arr.push((m_char.ord + offset - 'A'.ord) % 26 + 'A'.ord)
elsif m_char.match(/[a-z]/)
msg_arr.push((m_char.ord + offset - 'a'.ord) % 26 + 'a'.ord)
else
msg_arr.push(m_char)
end
end
encrypted_msg = msg_arr.map {|m_char| m_char.chr}
return encrypted_msg.join
end
caesar_cipher("What a string!", 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment