Skip to content

Instantly share code, notes, and snippets.

@matugm matugm/caesar.rb
Last active Dec 10, 2019

Embed
What would you like to do?
Caesar cipher using Ruby
ALPHABET_SIZE = 26
def caesar_cipher(string)
shiftyArray = []
charLine = string.chars.map(&:ord)
shift = 1
ALPHABET_SIZE.times do |shift|
shiftyArray << charLine.map do |c|
((c + shift) < 123 ? (c + shift) : (c + shift) - 26).chr
end.join
end
shiftyArray
end
puts caesar_cipher("testing")
def caesar_cipher(string, shift = 1)
alphabet = Array('a'..'z')
encrypter = Hash[alphabet.zip(alphabet.rotate(shift))]
string.chars.map { |c| encrypter.fetch(c, " ") }
end
p caesar_cipher("testing").join
def caesar_cipher(string, shift = 1)
alphabet = Array('a'..'z')
non_caps = Hash[alphabet.zip(alphabet.rotate(shift))]
alphabet = Array('A'..'Z')
caps = Hash[alphabet.zip(alphabet.rotate(shift))]
encrypter = non_caps.merge(caps)
string.chars.map { |c| encrypter.fetch(c, c) }
end
p caesar_cipher("testingzZ1Z").join
@matugm

This comment has been minimized.

Copy link
Owner Author

matugm commented Apr 5, 2016

Check the tutorial that goes with this code here:
http://www.rubyguides.com/2015/03/caesar-cipher-in-ruby/

@esquinas

This comment has been minimized.

Copy link

esquinas commented Sep 19, 2016

Just in case someone favors one-liners, you could replace lines 2-8 with this one:

encrypter = ([*('a'..'z')].zip([*('a'..'z')].rotate(shift)) + [*('A'..'Z')].zip([*('A'..'Z')].rotate(shift))).to_h
@KINGSABRI

This comment has been minimized.

Copy link

KINGSABRI commented May 30, 2017

@matugm @esquinas thanks both

@gagande90

This comment has been minimized.

Copy link

gagande90 commented Nov 2, 2019

@matugm Thanks for sharing this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.