Method: RubyLabs::BitLab#encode
- Defined in:
- lib/bitlab.rb
#encode(s, type, opt = nil) ⇒ Object
Make a Message object for the characters in string s. The second parameter determines the code to use. It can be :ascii, :parity, a hash object that has code mappings for letters, or a Huffman tree. If a hash or tree is passed, the message type is set to :packed, otherwise it’s :unpacked. The encoding type is saved so it can be used later in decoding.
Example:
>> encode("atg", :ascii)
=> 01100001 01110100 01100111
>> nt_code
=> {"a"=>00, "c"=>10, "g"=>11, "t"=>01}
>> encode("atg", nt_code)
=> 000111
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
# File 'lib/bitlab.rb', line 122 def encode(s, type, opt = nil) if (type.class == Hash || type.class == Node) code = (type.class == Node) ? assign_codes(type) : type msg = Message.new(:packed) s.each_byte do |ch| msg << code[ch.chr] printf("%s: %s\n", ch.chr, code[ch.chr]) if opt == :trace end else msg = Message.new(:unpacked) s.each_byte do |ch| code = ch.code(8) code.add_parity_bit if type == :parity msg << code printf("%s: %s\n", ch.chr, code) if opt == :trace end end return msg end |