Q:

How do I write png hex values stored in a string to a png file in Ruby?

I have a png image hex values stored in a string but I want to write this to a new png file to be viewed. I currently using the Ruby code below (with a small png example) but the hex values are slightly off when I check the output in the new png file. Where am I going wrong?
png_hex = "89504e470d0a1a0a0000000d494844520000000d0000000d08030000004535144e0000000774494d4507d7041517171c5943ea76000000097048597300000b1100000b11017f645f910000000467414d410000b18f0bfc610500000015504c544500000086c1e01544706ba4da4a85c6386c9f427ab6583bfce90000000174524e530040e6d866000000434944415478da558d41120030040395c8ff9f5cd421dd0b6b02b3e198c24f1d22c72996bed1683c89ae3d2f4856ed6570795b317dec0da45aba04ad2e761cfb7a4228bb5cb30147915c409a0000000049454e44ae426082"

File.open("temp.png", "w"){|fh|
 fh.print png_hex.scan(/.{2}/).map{|u| u.to_i(16)}.pack("C*")
}

A:

Use "wb" instead of "w" to open the file in binary mode:

"b"  Binary file mode
     Suppresses EOL <-> CRLF conversion on Windows. And
     sets external encoding to ASCII-8BIT unless explicitly
     specified.

(source)
By the way, you can call 
IO#putc to directly write an 8-bit integer to the IO stream without having to create an array and packing integers:
File.open("temp.png", "wb"){|fh|
  png_hex.scan(/.{2}/) { |e| fh.putc(e.hex) }
}

