博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ruby trainning - decryption
阅读量:6930 次
发布时间:2019-06-27

本文共 957 字,大约阅读时间需要 3 分钟。

hot3.png

 

#author linxu
#decrypt the message of cipher.txt

module RubyTrain

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

    attr_reader :path

    def get_code_table

      begin
        file = File.new(, "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')

转载于:https://my.oschina.net/randy1986/blog/356360

你可能感兴趣的文章