From: Michael Morin Date: 2008-08-09T06:35:07+09:00 Subject: Re: [QUIZ] hexdump (#171) Matthew Moss wrote: > ## hexdump (#171) > > _Quiz idea provided by Robert Dober._ > > This week's quiz should be quick and easy for experienced Rubyists, > and a good lesson for beginners. Your task this week is to write a > utility that outputs a hex dump of the input. I did something a little different, I made a module that can be used to extend IO objects. This means you can extend any File or socket objects to become hex writers. Since I don't think you can "un-extend" an object, it would probably be best if you dup the IO object if you need to switch between hex and normal output. #!/usr/bin/env ruby # UziMonkey module HexWriter def self.extend_object(o) class << o alias_method :old_write, :write end super end def write(s) s.each_byte do|b| if @bytes % 16 == 0 and @address != 0 end_line new_line end write_byte b end end def new_file @address = 0 new_line end def end_line old_write " " * (16 - @bytes) old_write " #{@ascii}\n" end def new_line @bytes = 0 @address ||= 0 @ascii = "" old_write "%08x" % @address end def write_byte(b) old_write " %02x" % b @ascii << ((b.chr =~ /[[:print:]]/).nil? ? '.' : b.chr) @bytes += 1 @address += 1 end end hex = STDOUT.dup.extend HexWriter ARGV.each do|f| puts "File: #{f}" hex.new_file hex.write File.read(f) hex.end_line end -- Michael Morin Guide to Ruby http://ruby.about.com/ Become an About.com Guide: beaguide.about.com About.com is part of the New York Times Company