Created
June 4, 2020 14:27
-
-
Save violetguos/1a9bf6a921ac43160e208878d9cfda30 to your computer and use it in GitHub Desktop.
TOP's ruby project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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