From: Sander Land Date: 2006-07-18T03:03:34+09:00 Subject: Re: First ruby code, need hint on iterator On 7/17/06, Gerr wrote: > Hello, > > Consider the following code which generates a hexdump of a string: > ... > What would be the idiomatic solution for this in Ruby ? Any other comments on > the code are welcome as well, ofcourse If you want to do things with 16 bytes at a time, you might as well process them in groups of 16: require 'enumerator' module Dump def hexdump offset = 0 out = '' split('').each_slice(16) {|chars| hc = chars.map{|c| "%02x " % c[0] } hex = hc[0..7] << '- ' << hc[8..15] str = chars.map{|c| (c[0] >= 32 && c[0] <= 127) ? c : "." } out << sprintf("%08x: %-50s %s\n", offset, hex, str) offset += 16 } return out; end end or even: module Dump def hexdump offset = -16 split('').enum_slice(16).map {|chars| hc = chars.map{|c| "%02x " % c[0] } hex = hc[0..7] << '- ' << hc[8..15] str = chars.map{|c| (c[0] >= 32 && c[0] <= 127) ? c : "." } sprintf("%08x: %-50s %s\n", offset += 16, hex, str) }.join end end