title: Sort Ruby Hash by order in array of keys
body: <p>I have a hash:</p>
  
  <pre><code>sample = { bar: 200, foo: 100, baz: 100 }
  </code></pre>
  
  <p>How do I sort <code>sample</code> using the order of keys in <code>sort_order</code>:</p>
  
  <pre><code>sort_order = [:foo, :bar, :baz, :qux, :quux]
  </code></pre>
  
  <p>Expected result:</p>
  
  <pre><code>sample #=&gt; { foo: 100, bar: 200, baz: 100 }
  </code></pre>
  
  <p>All I can come up with is</p>
  
  <pre><code>new_hash = {}
  sort_order.each{|k| new_hash[k] = sample[k] unless sample[k].nil? }
  sample = new_hash
  </code></pre>
  
  <p>There's got to be a better way. Hints?</p>
  
  <p>Keys without values should not be present, i.e. number of keys remain the same, which isn't the case with <a href="https://stackoverflow.com/questions/36302058/sort-hash-keys-based-on-order-of-same-keys-in-array">Sort Hash Keys based on order of same keys in array</a></p>