Last active
September 16, 2023 05:23
-
-
Save matugm/db363c7131e6af27716c to your computer and use it in GitHub Desktop.
Caesar cipher using Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@che30 Very very slick. Essentially:
string.chars.map(&:ord)
can be replaced withstring.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?