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] <=> b[attr]
end
break
end
end
result
end
end
p sort([{:a => 1},{:a => nil},{:a => 2}], :a)
#=> [{:a=>1}, {:a=>2}, {:a=>nil}]
p sort([{:a => nil},{:a => 'x'},{:a => 'a'}], :a)
#=> [{:a=>"a"}, {:a=>"x"}, {:a=>nil}]
My solution looks quite complex. Is there a better way to achieve the ordering in Ruby?