Sort array of hashes with nil values last I wrote a method which sorts an array of hashes by given hash keys. The method should put nil values at the end.

def sort(records, *attrs)
  records.sort do |a,b|
    result = 0
    attrs.each do |attr|
      unless a[attr] == b[attr]
        result = if a[attr].nil?
                   1
                 elsif b[attr].nil?
                   -1
                 else
                  a[attr] &lt;=&gt; b[attr]
                 end
        break
      end
    end
    result
  end
end

p sort([{:a =&gt; 1},{:a =&gt; nil},{:a =&gt; 2}], :a)
#=&gt; [{:a=&gt;1}, {:a=&gt;2}, {:a=&gt;nil}]
p sort([{:a =&gt; nil},{:a =&gt; 'x'},{:a =&gt; 'a'}], :a)
#=&gt; [{:a=&gt;"a"}, {:a=&gt;"x"}, {:a=&gt;nil}]


My solution looks quite complex. Is there a better way to achieve the ordering in Ruby?
You can create temporary sorting columns:

def sort records, *attrs
  records.sort_by do |h|
    h.values_at(*attrs).map do |v|
      v.nil? ? [2] : [1, v]
    end
  end
end


Here I added columns with values 1 or 2 to the left for higher priority -- could add to the right or even in between for more complex sorting.