Skip to content

Instantly share code, notes, and snippets.

@aslam
Created November 16, 2018 11:07
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 aslam/5a2db0af06781a0adc7b39e90369e8b4 to your computer and use it in GitHub Desktop.
Save aslam/5a2db0af06781a0adc7b39e90369e8b4 to your computer and use it in GitHub Desktop.
A simple implementation of Caesar's Cipher.
puts "Welcome!"
puts "Please enter the phrase you wish to encrypt: "
phrase = gets.chomp
puts "Enter factor: "
factor = gets.chomp.to_i
ALPHABETS = {
'lower' => [nil, ('a'..'z').to_a].flatten,
'upper' => [nil, ('A'..'Z').to_a].flatten
}
def ceaser_cipher2(phrase, factor = 1)
return if phrase.strip.empty?
limit = ALPHABETS['lower'].size - 1
phrase.split("").map do |char|
if !char.strip.empty? && (ALPHABETS['lower'].include?(char) || ALPHABETS['upper'].include?(char))
ref = /[[:upper:]]/.match(char) ? 'upper' : 'lower'
index = ALPHABETS[ref].index(char)
factored = index + factor
if (factored > limit)
factored = factored - limit
end
char = ALPHABETS[ref][factored]
end
char
end.join
end
encrypted = ceaser_cipher2(phrase, factor)
puts "Encrypted phrase: '#{encrypted}'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment