title: Sorting hash with custom comparator in ruby
body: <p>I have a array of hashes that should be fairly simple to sort, but since I'm very new to ruby and still looking into documents I'm having issues to sort a hash that has few key value combinations but needs to be sorted based on multiple key values.</p>
  
  <pre><code>[{:attr1 =&gt; 3, :attr2 =&gt; 'test', attr3 =&gt; 'test2'}, 
  {:attr1 =&gt; 1, :attr2 =&gt; 'test', attr3 =&gt; nil}, 
  {:attr1 =&gt; 1, :attr2 =&gt; 'test', attr3 =&gt; 'test3'},
  {:attr1 =&gt; 2, :attr2 =&gt; 'test', attr3 =&gt; 'test3'}]
  </code></pre>
  
  <p>So I'd like to sort it according to custom rule. And custom rule would be first take a look at <code>attr1</code> and sort according to it in descending order.</p>
  
  <p>If there are same <code>attr1</code> values but one of those <code>attr3</code> is <code>nil</code> then order those with nil last.</p>
  
  <p>So I think I would need to create custom comparator, or not. How can I do this with the least amount of pain?</p>
  
  <p>If this was to be sorted it would look like this :</p>
  
  <pre><code>[{:attr1 =&gt; 3, :attr2 =&gt; 'test', attr3 =&gt; 'test2'}, 
      {:attr1 =&gt; 2, :attr2 =&gt; 'test', attr3 =&gt; 'test3'},
      {:attr1 =&gt; 1, :attr2 =&gt; 'test', attr3 =&gt; 'test3'},
      {:attr1 =&gt; 1, :attr2 =&gt; 'test', attr3 =&gt; nil}
  ]
  </code></pre>