Avatar

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"

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 !

Aedd89a10aba3a46576ea4f604146c65

Carl Porth

August 9, 2008, August 09, 2008 06:49, permalink

No rating. Login to rate!

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
Be1e3ee645d23c95ba650c21bc885927

Fabien Jakimowicz

August 9, 2008, August 09, 2008 11:34, permalink

No rating. Login to rate!
1
2
3
def caesar(text, shift)
  text.split('').collect {|letter| (letter[0] + shift).chr}.join
end
1e8f141e7857d397d8020ed3b759e88a

Maciej Piechotka

August 10, 2008, August 10, 2008 18:43, permalink

No rating. Login to rate!

Modification of Fabien Jakimowicz's code

1
2
3
def caesar(text, shift)
  text.split('').collect! {|letter| (letter[0] + shift).chr}.join
end

Your refactoring





Format Copy from initial code

or Cancel