Last active
February 3, 2017 03:20
-
-
Save opan/4bbf1271444a688621534168a44865f0 to your computer and use it in GitHub Desktop.
Solving ROT13 Algorithm logic in Ruby
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
#!/usr/bin/env ruby | |
str = "Jul qvq gur puvpxra pebff gur ebnq?" | |
def rot13(secret_messages) | |
upcase_alphabet = ("A".."Z").to_a | |
downcase_alphabet = ("a".."z").to_a | |
upcase_rot13 = [] | |
upcase_length = upcase_alphabet.length | |
downcase_length = downcase_alphabet.length | |
upcase_alphabet.each_with_index do |c, i| | |
if (i + 13) >= upcase_length | |
upcase_rot13 << upcase_alphabet[(i + 13) - upcase_length] | |
else | |
upcase_rot13 << upcase_alphabet[(i + 13)] | |
end | |
end | |
downcase_rot13 = [] | |
downcase_alphabet.each_with_index do |c, i| | |
if (i + 13) >= downcase_length | |
downcase_rot13 << downcase_alphabet[(i + 13) - downcase_length] | |
else | |
downcase_rot13 << downcase_alphabet[(i + 13)] | |
end | |
end | |
joined_alphabet = upcase_alphabet + downcase_alphabet | |
joined_rot13 = upcase_rot13 + downcase_rot13 | |
decrypted_messages = [] | |
secret_messages.each do |str| | |
tmp_result = [] | |
str.each_char do |c| | |
if /[A-Za-z]/.match c | |
tmp_result << joined_rot13[joined_alphabet.find_index(c)] | |
else | |
tmp_result << c | |
end | |
end | |
decrypted_messages << tmp_result | |
end | |
decrypted_messages | |
end | |
rot13(str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment