Skip to content

Instantly share code, notes, and snippets.

@SimplGy
Created October 10, 2013 17:35
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 SimplGy/6922370 to your computer and use it in GitHub Desktop.
Save SimplGy/6922370 to your computer and use it in GitHub Desktop.
Ruby Implementation of a Rotational Cipher. Wrote in https://coderpad.io/966172
$ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
$alphabet = 'abcdefghijklmnopqurstvwxyz'
# Get an index of an alphabetic letter based on the index and offset
def calculateOffset(index, offset)
index += offset
index -= 26 while index >= 26 # keep subtracting until we get to the right range
index
end
# Get a char from the alphabet based on an offset
def getCharByOffset(char, offset=0)
# Chars could be in the upper alphabet, the lower alphabet, or neither.
indexUpper = $ALPHABET.index(char)
indexLower = $alphabet.index(char)
if indexUpper
i = calculateOffset(indexUpper, offset)
char = $ALPHABET[i].chr # Get the char at that index
elsif indexLower
i = calculateOffset(indexLower, offset)
char = $alphabet[i].chr
end
char
end
# Rotationally encode a string
def rotx(x, string, encrypt=true)
newString = ''
x = -x unless encrypt
# for each char in the string
string.each_char do |char|
# TODO: support decryption
newString << getCharByOffset(char, x)
end
# get a new char that is `x` away in the alphabet
newString
end
# ------------------------------------------------ Assertions
puts rotx 10, 'Hello, World'
# => "Rovvy, Gybvn" # Shouldn't this be "Rovvy, Gycvn"?
puts rotx 10, 'Rovvy, Gycvn', false
# => "Hello, World"
# Rotation numbers greater than 26 should work as well
puts rotx 36, 'Hello, World'
# => "Rovvy, Gybvn"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment