Skip to content

Instantly share code, notes, and snippets.

@nerdinand
Created June 11, 2018 06:34
Show Gist options
  • Save nerdinand/c8f1dad23f66bc11421e1e85a4309cb0 to your computer and use it in GitHub Desktop.
Save nerdinand/c8f1dad23f66bc11421e1e85a4309cb0 to your computer and use it in GitHub Desktop.
Caesar encryption in Ruby
ALPHABET = /^[A-Z]+$/
COMMANDS = ['encrypt', 'decrypt']
command = ARGV[0]
key = ARGV[1].to_i
text = ARGV[2]
if COMMANDS.include? command
if ALPHABET =~ text
encrypted = text.chars.map do |character|
(65 + (character.ord - 65 + key) % 26).chr
end.join
puts encrypted
else
puts "Error: Input does not match allowed alphabet (A-Z)"
end
else
puts "Error: command must be one of #{COMMANDS.join(', ')}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment