Skip to content

Instantly share code, notes, and snippets.

@johnwahba
Created October 30, 2013 19:35
Show Gist options
  • Save johnwahba/7238808 to your computer and use it in GitHub Desktop.
Save johnwahba/7238808 to your computer and use it in GitHub Desktop.
Cipher implementation ruby
def rotx(x, string, encrypt=true)
offset = encrypt ? x : -x
uppers = Hash[("A".."Z").zip(("A".."Z").to_a.rotate(offset))]
lowers = Hash[("a".."z").zip(("a".."z").to_a.rotate(offset))]
dictionary = uppers.merge(lowers)
output = ""
string.length.times do |idx|
char = string[idx]
if dictionary[char]
output += dictionary[char]
else
output += char
end
end
output
end
p rotx 10, 'Hello, World'
# => "Rovvy, Gybvn"
p rotx 10, 'Rovvy, Gybvn', false
# => "Hello, World"
# Rotation numbers greater than 26 should work as well
p rotx 36, 'Hello, World'
# => "Rovvy, Gybvn"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment