-
Notifications
You must be signed in to change notification settings - Fork 1
/
huffman.rb
38 lines (31 loc) · 837 Bytes
/
huffman.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env ruby
#
# Huffman encoder/decoder. See:
# http://en.nerdaholyc.com/huffman-coding-on-a-string/
require 'optparse'
require './coder.rb'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: huffman.rb [options]"
opts.on("-m", "--mode MODE", [:encode, :decode], "Set the mode: encode/decode") do |m|
options['mode'] = m
end
end.parse!
if options['mode'].nil?
puts "You must specify a mode: encode/decode"
Kernel::exit(FALSE)
end
if ARGV.length == 0
puts "You must specify some text to #{options['mode']}"
Kernel::exit(FALSE)
end
case options['mode']
when :encode
encoded = HuffmanCoder::encode(ARGV.join(" "))
puts encoded.to_s # encoded binary string
when :decode
puts HuffmanCoder::decode(ARGV.join(" ")).plaintext
else
puts "Invalid mode"
Kernel::exit(FALSE)
end