Sha256: e1b8692df5a64d939eda45dc24e2ae99032490724cf6cffab39bfa74a8bbb47f

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

module Encrubto::Caesar
    class Encryptor 
    
      ORIGINAL = 'abcdefghijklmnopqrstuvwxyz'

      def encrypt(str, offset)
        if str.is_a?(String) && offset.is_a?(Integer)
          if 0 <= offset && offset <= 26
            caesar = shift(offset)
            str.tr("#{ ORIGINAL }#{ ORIGINAL.upcase }", "#{ caesar }#{ caesar.to_s.upcase }")
          else
            raise 'Offset must be between 0 and 26!'
          end
        else
          raise 'First param must be String, second param must be Integer!'
        end
      end
  
      def decrypt(encrypted, offset)
        if encrypted.is_a?(String) && offset.is_a?(Integer)
          if 0 <= offset && offset <= 26
            caesar = shift(offset)
            encrypted.tr("#{ caesar }#{ caesar.to_s.upcase }", "#{ ORIGINAL }#{ ORIGINAL.upcase }")
          else
            raise 'Offset must be between 0 and 26!'
          end
        else
            raise 'First param must be String, second param must be Integer!'
        end
      end

      def shift(offset)
        caesar_first_part = ORIGINAL[offset..ORIGINAL.length-1]
        caesar_second_part = ORIGINAL[0..offset-1]
        caesar_first_part.to_s + caesar_second_part.to_s
      end

    end
  end
  

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
encrubto-0.2.0 lib/encrubto/caesar/encryptor.rb