title: Ruby Write Hex String To Binary File By Keeping Hex Values
body: <p>I want to generate random bytes in Ruby, but I also want to insert some  constant values into specific positions of  the random bytes.</p>
  
  <pre><code>random_hex_string = SecureRandom.hex (length)
  random_hex_string.insert(0,"0102")
  random_hex_string.insert(30*1,"36")
  </code></pre>
  
  <p>So I generate random hex bytes and insert my hex values there. The problem is that I have now a string not a byte array. So when I print it:</p>
  
  <pre><code>File.open("file.txt", 'w+b') do |f|
  f.write(random_hex_string)
  </code></pre>
  
  <p>It - not surprisingly - converts the hex string into binary then writes it. So my hex values are not kept. To be more clear, when I write my hex string to the file, and then I want to see the same hex values when I hex dump the file. How can I do this?  </p>