title: How to truncate data in a hash so that the resulting JSON isn't longer than n bytes?
body: <p>I have a hash that looks something like this:</p>
  
  <pre><code>{ :a =&gt; "some string", :b =&gt; "another string", :c =&gt; "yet another string" }
  </code></pre>
  
  <p>I wan't to call <code>to_json</code>on it eventually, but the resulting json-string cannot be longer than <code>n</code> bytes. </p>
  
  <p>If the string is too big, then first <code>:c</code> should be truncated first. If that's not enough, <code>:b</code> should be truncated. Finally <code>:a</code>. Also the strings can contain multi-byte characters like German umlauts and the Ruby version is 1.8.7. (The umlauts first take 2 bytes, but as json they are 5 bytes long.)</p>
  
  <p>What I wrote was a loop that converts the hash to_json and checks the length. If its less or equal <code>n</code> it's returned, otherwise I concat the values of <code>:a</code> + <code>:b</code> + <code>:c</code> and shorten by half. If the new hash is too big(small), I shorten(extend) by 1/4th, 1/8th, 1/16th of the original string. Finally I get length of <code>hash.as_json == n</code>.</p>
  
  <p>It all feels very hackish and although all tests check out I'm not sure that's even stable.</p>
  
  <p>Does anyone have a good suggestion how to solve this properly?</p>