Gerr
7/17/2006 12:40:00 PM
Hello,
Consider the following code which generates a hexdump of a string:
----------------------------------------------------------------------
#!/usr/bin/ruby
module Dump
def hexdump
x = 0
offset = 0
hex = ""
str = ""
out = ""
each_byte { |c|
x = x + 1
hex << sprintf("%02x ", c)
hex << "- " if(x == 8)
str << ((c >= 32 && c<=127) ? c.to_i.chr : ".")
if(x == 16)
out << sprintf("%08x: %-50s %s\n", offset, hex, str)
x = 0
hex = ""
str = ""
offset = offset + 16
end
}
out << "\n"
return out
end
end
l = $stdin.read(10000)
l.extend Dump
print l.hexdump
----------------------------------------------------------------------
This program has a serious flaw: only if 16 bytes are collected from the input,
a new line with hex codes is printed. If the input string has a length that is
not a multiple of 16, the remaining bytes will not be handled.
A solution would be to duplicate the line
out << sprintf("%08x: %-50s %s\n", offset, hex, str)
somewhere at the end of the loop, so that any remaining buffers are printed.
This forces me to duplicate code, though, which is not what I want.
The obvious solution for me would be to change the line
if(x == 16)
to something like
if((x == 16) || (c.is_the_last_element_from_the_set))
The problem is in the fictional thingy 'is_the_last_element_from_the set',
which I believe is not available.
What would be the idiomatic solution for this in Ruby ? Any other comments on
the code are welcome as well, ofcourse
Thank you