On May 17, 2008, at 3:15 PM, Tim Hunter wrote: > Since nobody else has any Ruby to talk about today... :-) > > My gut feel is that this should be 2 or 3 lines of code but for some > reason I'm missing the trick. > > I need a script that converts pairs of hex digits into their decimal > equivalents. Suppose the script accepts a single argument, a string > composed of hex digits, either upper- or lower-case, or both, possibly > with embedded blanks. For the sake of argument let's say that there's > always going to be at least 1 pair but never more than, oh, 20 pairs > (or > as many as can easily be typed on a command line). > > The script should remove any embedded blanks from the argument, then > go > through the string left-to-right. For each pair of hex digits, display > the value of the pair as a 3-digit decimal number, separated with a > backslash. > > So, for example, > > ruby hex2dec.rb "f0 d7e2 28" => \240\215\226\040 > > Ideas? A bit different that Ara's, but this is a nearly method-for-word translation: class String def h2d [self.gsub(/\s+/,'')]. # remove embedded blanks pack('H*'). # convert hex pairs to bytes split(//). # array of single-byte strings map{|c| "%03d"%[c[0]]}. # first(only) char as 3 decimal-digits join('\\') # separated by backslash end end Of course, that's not a script, but a method. In case this is homework, that part is left as an exercise. ;-) -Rob Rob Biedenharn http://agileconsultingllc.com Rob / AgileConsultingLLC.com