Skip to content

Instantly share code, notes, and snippets.

@matugm
Last active September 16, 2023 05:23
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save matugm/db363c7131e6af27716c to your computer and use it in GitHub Desktop.
Save matugm/db363c7131e6af27716c to your computer and use it in GitHub Desktop.
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
Copy link
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
Copy link

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
Copy link

@matugm @esquinas thanks both

@gagande90
Copy link

@matugm Thanks for sharing this.

@CharlesIvia
Copy link

Thank you.
...

@SamGarner
Copy link

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
Copy link

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)

@SteveBenner
Copy link

SteveBenner commented Apr 6, 2022

@che30 Very very slick. Essentially:

string.chars.map(&:ord) can be replaced with string.bytes

Array.pack can be used to boil down a lot of the enumerable code seen in the original example, but be warned--You MUST speficially pass 'c*' as the argument, otherwise badness happens.

I am however curious, why did you feel the need to call downcase on the string input? Does it change anything?

@odilson-dev
Copy link

Awesome @matugm Thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment