title: Complex sorting and data collection
body: <p>I have a hash of order details and the details are in an array. From that I want to collect a list unique user names. For this I want to sort the array based on order date time in reverse (i.e. last order becomes first) and if order date time is not available, sort it based on order id. So the names in the list would be ones who have order date time and places the names without order date time at the end of the list. Below is my hash:</p>
  
  <pre><code>{
      "orderDetails": [
          {
              "orderId": 11,
              "orderDtTm": "2016-08-04T19:39:06.000Z",
              "orderTz": "America/Chicago",
              "user": {
                  "userId": 1,
                  "userName": "Joe, SMITH"
              }
          },
          {
              "orderId": 10,
              "user": {
                  "userId": 2,
                  "userName": "Lynn, WILSON"
              }
          },
          {
              "orderId": 25,
              "orderDtTm": "2016-08-04T20:39:06.000Z",
              "orderTz": "America/Chicago",
              "user": {
                  "userId": 1,
                  "userName": "Joe, SMITH"
              }
          },
          {
              "orderId": 33,
              "user": {
                  "userId": 3,
                  "userName": "Mark, Taylor"
              }
          },
          {
              "orderId": 16,
              "orderDtTm": "2016-08-04T21:53:09.000Z",
              "orderTz": "America/Chicago",
              "user": {
                  "userId": 3,
                  "userName": "Mark, Taylor"
              }
          }
      ]
  }
  </code></pre>
  
  <p>Since orders 1, 3 and 5 have order date time, my initial list would be sorted based on last order placed which would be order 5, 3 and 1 i.e. <code>["Mark, Taylor", "Joe, SMITH", "Joe, SMITH"]</code> and the add the other names based on order id since they don't have order date time which would be order 4 and then 2. So my array at the end would be <code>["Mark, Taylor", "Joe, SMITH", "Joe, SMITH", "Mark, Taylor", "Lynn, WILSON"]</code>.</p>
  
  <p>Since I want the unique user names I would do:</p>
  
  <p><code>["Mark, Taylor", "Joe, SMITH", "Joe, SMITH", "Mark, Taylor", "Lynn, WILSON"].uniq</code> on it to get <code>["Mark, Taylor", "Joe, SMITH", "Lynn, WILSON"]</code></p>
  
  <p>My code:</p>
  
  <pre><code>order_details = order_details_data[:orderDetails]
  
  order_details_array = order_details.sort_by { |key| key[:orderDtTm]|| key[:orderId] }.reverse
  user_names_set = Set.new
  
  order_details_array.each do |obj|
      user_name = obj[:user][:userName]
      user_names_set &lt;&lt; user_name unless user_name.blank?
  end
  </code></pre>
  
  <p>This works fine if I always have order date time, but give unexpected output when I don't have the order date time for some of the details.</p>