Take the 2-minute tour ×

I need to create a script that converts a 4 byte input into its reversed form. I imagine the basic algorithm is something like

  1. Read input from STDIN
  2. Convert to byte array
  3. Reverse the array
  4. Write bytes on STDOUT

Any help greatly appreciated.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

It reads four bytes from STDIN, unpacks the string as a list of 8 bit unsigned integers, reverses the list and then packs it back as 8 bit unsigned integers.

share|improve this answer
Thanks, that was exactly what I needed. –  mikelong Jul 7 '11 at 14:20

EDIT: Theo did a much better job at doing this, disregard my comment except for last paragraph. :] I'd like to do this with collect, but I don't know how to make collect work on each char instead of line, so I'll use each_byte method. We collect all the bytes, make them characters, push them into the array.

Then we output the whole thing reversed and joined with nothing — "". You might want to write print or $<.write instead of puts, cause it might add some additional new lines.

byte_array = []
$stdin.each_byte { |byte| byte_array << byte.chr }

puts byte_array.reverse.join('')

What I did there wasn't right, though, that's spoonfeeding. You should've found a book, like why's poignant guide to ruby http://mislav.uniqpath.com/poignant-guide/ , searched ruby docs and used google to write this. It'd've been much more valuable to you than asking stack overflow, IMO.

share|improve this answer
I started out doing more or less what you suggest: $stdin.read(4).each_byte.to_a.reverse.join. I think #each_byte isn't in 1.8 though, only 1.9. –  Theo Jul 7 '11 at 14:29

Your Answer


