Skip to content

Instantly share code, notes, and snippets.

@MatthewRiggott
Created May 3, 2015 19:22
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 MatthewRiggott/4d39a0d95077edc904f8 to your computer and use it in GitHub Desktop.
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.
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