We can sort ruby hash by two keys like below.
1 2 3 4 |
array.sort!{|a, b| a[:value_1] <=> b[:value_1] || a[:value_2] <=> b[:value_2] } |
Well, how we can sort by three keys?
1 2 3 4 5 |
array.sort{|a, b| a[:value_1] <=> b[:value_1] || a[:value_2] <=> a[:value_2] || a[:value_3] <=> b[:value_3] } |
So, how about make function to sort hash?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# @param [Array] array the hash array which you want to compare elements # @param [Array] value_names value name to compare, like [:value_1, :value_2, ...] # @param [Array] orders compare order. To compare order like SQL # 'order by value_1 desc, value_2 asc' then [-1, 1] def multicompare(a, b, value_names, orders) if value_names.length == 0 return 0 else value_name = value_names[0] return (orders[0] * (a[value_name] <=> b[:value_name])) || multicompare(a, b, value_names[1..-1], orders[1..-1]) end end array.sort{|a, b| multicompare(a, b, [:value_1, :value_2, :value_3], [1, -1, 1]) } |