1 2 3 4 5 6 7 8 9 10
def caesar(text,shift) count = 0 decoded = '' while(count<text.size) decoded << (text[count]+shift).chr count += 1 end decoded end
Refactorings
No refactoring yet !
Carl Porth
August 9, 2008, August 09, 2008 06:49, permalink
I've always seen shifts done with the unix tr command. You can do the same in ruby. Additionally this method handles the rotation of chars like
caesar("ABCDEF",22) #=> "WXYZAB"
1 2 3 4 5
def caesar(text,n) alpha = ('A'..'Z').to_a n.times { alpha.push(alpha.shift) } text.tr('A-Z', alpha.join) end
Fabien Jakimowicz
August 9, 2008, August 09, 2008 11:34, permalink
1 2 3
def caesar(text, shift) text.split('').collect {|letter| (letter[0] + shift).chr}.join end
Maciej Piechotka
August 10, 2008, August 10, 2008 18:43, permalink
Modification of Fabien Jakimowicz's code
1 2 3
def caesar(text, shift) text.split('').collect! {|letter| (letter[0] + shift).chr}.join end
A Caesar Cipher, or Caesar Shift, is a simple encryption method which substitutes the letter based on a fixed number movement. An example:
if the shift is set at 1,
than
caesar("ABCDEF",1) #=> "BCDEFG"