Skip to content

Instantly share code, notes, and snippets.

@matugm

matugm/caesar.rb

Last active Aug 23, 2020
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 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 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 KINGSABRI commented May 30, 2017

@matugm @esquinas thanks both

@gagande90

This comment has been minimized.

Copy link

@gagande90 gagande90 commented Nov 2, 2019

@matugm Thanks for sharing this.

@CharlesIvia

This comment has been minimized.

Copy link

@CharlesIvia CharlesIvia commented Mar 28, 2020

Thank you.
...

@SamGarner

This comment has been minimized.

Copy link

@SamGarner SamGarner commented Jul 23, 2020

Thank you for this. I see two things I believe should be updated:

example 1:
((c + shift) < 123 ? (c + shift) : (c + shift) - 26).chr
to
((c + shift) < 123 ? (c + shift).chr : (c + shift) - 26).chr

example 2 (to handle characters outside of a..z ):
string.chars.map { |c| encrypter.fetch(c, " ") }
to
string.chars.map { |c| encrypter.fetch(c, c) }

@che30

This comment has been minimized.

Copy link

@che30 che30 commented Aug 23, 2020

Good congrats!! but I got this way of doing also
def cipher(string,key)
namem=[]
string.downcase.bytes.map do|c|
namem.push(c+key<123?(c+key):(c+key-26))
end
namem.pack('c*')
end
puts cipher('What a string!',5)

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.