# Late huffman (quiz 123)

**URL:** <https://www.ruby-forum.com/t/late-huffman-quiz-123/225948>\
**Category:** Ruby\
**Created:** [May 17, 2007, 12:50am UTC](https://www.ruby-forum.com/t/late-huffman-quiz-123/225948 "2007-05-17T00:50:33Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![kyle\_s](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f6c823/32.png) [@kyle\_s](https://www.ruby-forum.com/u/kyle_s)\
**Post date:** [May 17, 2007, 12:50am UTC](https://www.ruby-forum.com/t/late-huffman-quiz-123/225948/1 "2007-05-17T00:50:33Z")

</div>

So it’s rather late to post this, but I spent the time writing it, so  
why not?  
I was hoping I could get a few pointers also, on making this well…  
more ruby like.

Perhaps more efficient, more right, etc.

#huffman encoding by dummies  
class Huffman  
def initialize(string)  
@sourcestring=string  
@translationtable=nil  
@encoded=nil  
@prettyencoded=nil  
@decoded=nil  
end  
attr\_accessor :sourcestring  
attr\_reader :encoded,:translationtable,:decoded,:prettyencoded  
def maketranslationtable()  
@translationtable=Hash.new(0)  
@sourcestring.split(’’).each{|l|  
@translationtable.store(l,@translationtable[l]+1)}  
count=0  
@translationtable.collect{|a| a[0],a[1]=a[1],a[0]}.sort.reverse.each  
do  
|letter|  
@translationtable.store(letter[1],(“1”\*count+“0”).to\_i)  
count+=1  
end  
@translationtable[@translationtable.invert.max[1]]/=10  
end

def translationtable=(newtranslationtable)  
@translationtable=newtranslationtable if  
newtranslationtable.class==@translationtable.class  
puts “with a new translationtable, prettymuch everything needs  
clearing”  
@sourcestring=nil  
@encoded=nil  
@prettyencoded=nil  
@decoded=nil  
end

def encoded=(data)  
@encoded=data  
puts “with new encoded data, many thigns need to be cleared”  
@sourcestring=nil  
@prettyencoded=nil  
@decoded=nil  
end

def encode()  
maketranslationtable() if @translationtable.nil?  
@encoded=@sourcestring.split(’’).collect{|i|  
@translationtable[i]}.join  
end  
def decode()  
if @translationtable.nil? then  
puts “Can’t decode without a translation table!”  
else  
@decoded=@encoded.clone  
@translationtable.invert.to\_a.sort.reverse.each do  
|pair|  
@decoded.gsub!(pair[0].to\_s,pair[1])  
end  
end  
end

def prettyprint(byte=8,bytes=5)  
encode() if @encoded.nil?  
@prettyencoded=""  
@encoded.gsub(/([01]{#{byte}})/){|i| “#{i} “}.split.each\_with\_index  
do  
|num,index|  
@prettyencoded+=”#{num}#{(index+1)%bytes==0?”\n":’ '}"  
end  
@prettyencoded+="\n"  
end

def to\_s()  
prettyprint() if @prettyencoded.nil?  
decode() if @decoded.nil?  
“#{@decoded}\n#{@prettyencoded}”  
end

private :prettyprint  
end

h=Huffman.new(ARGV.join(’ '))  
puts h
