Last active
June 25, 2021 23:34
-
-
Save airicbear/9c0e947e556970ad5964a0018d59164a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# frozen_string_literal: true | |
def wrap_lower?(char, shifted_char, range) | |
range.include?(char) && !range.include?(shifted_char) | |
end | |
def wrap_upper?(char, shifted_char, range) | |
range.include?(char) && !range.include?(shifted_char) | |
end | |
def wrap(char, shifted_char, lowercase_range = 'a'.ord..'z'.ord, uppercase_range = 'A'.ord..'Z'.ord) | |
if wrap_lower?(char, shifted_char, lowercase_range) | |
'a'.ord + (shifted_char - 'a'.ord) % lowercase_range.size | |
elsif wrap_upper?(char, shifted_char, uppercase_range) | |
'A'.ord + (shifted_char - 'A'.ord) % uppercase_range.size | |
else | |
shifted_char | |
end | |
end | |
def letter?(char) | |
char.upcase != char.downcase | |
end | |
def caesar_cipher(string, shift) | |
string.chars.map do |char| | |
if letter?(char) | |
wrap(char.ord, char.ord + shift).chr | |
else | |
char | |
end | |
end.join | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment