Last active
March 15, 2016 17:36
-
-
Save alopatindev/d0c7e384106cdff357e0 to your computer and use it in GitHub Desktop.
caesar.rb
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 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