Skip to content

Instantly share code, notes, and snippets.

@alopatindev
Last active March 15, 2016 17:36
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 alopatindev/d0c7e384106cdff357e0 to your computer and use it in GitHub Desktop.
Save alopatindev/d0c7e384106cdff357e0 to your computer and use it in GitHub Desktop.
caesar.rb
def is_letter (x)
return x.ord >= "a".ord && x.ord <= "z".ord
end
def encrypt (text, key, n, offset)
encrypted_text = ""
text.each_char do |x|
if is_letter(x)
code = (x.ord + key - offset) % n + offset
encrypted_text += code.chr
else
encrypted_text += x
end
end
return encrypted_text
end
def decrypt (encrypted_text, key, n, offset)
text = ""
encrypted_text.each_char do |y|
if is_letter(y)
code = (y.ord - key + n - offset) % n + offset
text += code.chr
else
text += y
end
end
return text
end
key = 123
offset = "a".ord
n = "z".ord - offset + 1
text = "helloz there"
encrypted_text = encrypt text, key, n, offset
puts encrypted_text
raise "fail" unless (decrypt encrypted_text, key, n, offset).eql? text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment