Skip to content

Instantly share code, notes, and snippets.

@airicbear
Last active June 25, 2021 23:34
Show Gist options
  • Save airicbear/9c0e947e556970ad5964a0018d59164a to your computer and use it in GitHub Desktop.
Save airicbear/9c0e947e556970ad5964a0018d59164a to your computer and use it in GitHub Desktop.
# 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