File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ # Caesar Cipher replaces characters rotating X number of positions to the left or to the right. 
2+ # 
3+ # Alphabet 
4+ # a b c d e f g h i j k l m n o p q r s t u v w x y z 
5+ # 
6+ # shift 4 >> it means to rotate 4 places 
7+ # 
8+ # After shifting 
9+ # e f g h i j k l m n o p q r s t u v w x y z a b c d 
10+ # 
11+ # plaintext -> apple 
12+ # ciphertext -> ettpi 
13+ 
14+ class  CaesarCipher 
15+   ALPHABET  =  ( 'a' ..'z' ) . to_a 
16+ 
17+   def  self . encrypt ( plaintext ,  shift ) 
18+     plaintext . chars . map  do  |letter |
19+       temp  =  letter . ord  + shift 
20+       temp  -= ALPHABET . length  while  temp  > 'z' . ord 
21+       temp . chr 
22+     end . join 
23+   end 
24+ 
25+   def  self . decrypt ( ciphertext ,  shift ) 
26+     ciphertext . chars . map  do  |letter |
27+       temp  =  letter . ord  - shift 
28+       temp  += ALPHABET . length  while  temp  < 'a' . ord 
29+       temp . chr 
30+     end . join 
31+   end 
32+ end 
33+ 
Original file line number Diff line number Diff line change 1+ require  'minitest/autorun' 
2+ require_relative  'caesar' 
3+ 
4+ class  CaesarCipherTest  < Minitest ::Test 
5+   def  test_shift4 
6+     run_tests ( 'apple' ,  'ettpi' ,  4 ) 
7+   end 
8+ 
9+   def  test_shift27 
10+     run_tests ( 'amateur' ,  'bnbufvs' ,  27 ) 
11+   end 
12+ 
13+   private 
14+ 
15+   def  run_tests ( plaintext ,  expected_cipher ,  shift ) 
16+     encrypted  =  CaesarCipher . encrypt ( plaintext ,  shift ) 
17+     assert_equal  encrypted ,  expected_cipher 
18+     decrypted  =  CaesarCipher . decrypt ( encrypted ,  shift ) 
19+     assert_equal  decrypted ,  plaintext 
20+   end 
21+ end 
22+ 
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments