From: Gerr Date: 2006-07-18T04:50:04+09:00 Subject: Re: First ruby code, need hint on iterator Sander Land wrote: > 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 Delightful ! It's hard to think outside the box if you mainly have been programming C for 20 years... Thank you very much, I will learn a *lot* from this newsgroup, I'm sure :)