Created
May 3, 2015 19:22
-
-
Save MatthewRiggott/4d39a0d95077edc904f8 to your computer and use it in GitHub Desktop.
Ruby code that takes a string with an integer value and shifts each character by the integer value.
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_cypher(word, shift_amount) | |
result = "" | |
word.each_char do |character| | |
letter_value = character.ord | |
if (97..122).include?(letter_value) | |
# shift lowercase letters | |
result += (((letter_value - 97 + shift_amount) % 26) + 97).chr | |
elsif (65..90).include?(letter_value) | |
# shift the uppercase letters | |
result += (((letter_value - 65 + shift_amount) % 26) + 65).chr | |
else | |
# everything else doesn't get shifted | |
result += character | |
end | |
end | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment