ruby trainning - decryption

 


#author linxu
#decrypt the message of cipher.txt

module RubyTrain
  SPLIT_KEY = ":"
  class Decoder
    def initialize(path)
      @path = path
      @code_table = Hash.new
      get_code_table
    end

    attr_reader :path

    def get_code_table
      begin
        file = File.new(@path, "r")
        while (line = file.gets)
          value,key = line.strip().split(SPLIT_KEY)
          @code_table.store(key, value)
        end
        file.close
      rescue => err
        raise err
      end
    end

    def decode(encrypted_message)
      decrypted_message = String.new
      encrypted_message.each_char{|e| decrypted_message << @code_table.fetch(e,e)}
      return decrypted_message
    end
   end
end

def get_cipher_message(path)
  cipher_message = String.new
  begin
    file = File.new(path, "r")
    while (line = file.gets)
      cipher_message << line
    end
    file.close
  rescue => err
    raise err
  end
  return cipher_message
end

coder = RubyTrain::Decoder.new './code_table.txt'
puts coder.decode 'b1EEA V3Pz!' # Hello Ruby!
puts coder.decode(get_cipher_message './cipher.txt')

你可能感兴趣的:(Ruby)