完全に精神的な解決策を使用することに抵抗がない場合は、次の方法が非常に気に入っています。
zipped = (1..5).zip [:push, :unshift].cycle
# => [[1, :push], [2, :unshift], [3, :push], [4, :unshift], [5, :push]]
[].tap { |result| zipped.each { |val, op| result.send op, val } }
# => [4, 2, 1, 3, 5]
module Enumerable
def to_podium
[].tap { |r| (zip [:push, :unshift].cycle).each { |v, o| r.send o, v } }
end
end
(1..10).to_podium
# => [10, 8, 6, 4, 2, 1, 3, 5, 7, 9]
そしてそれを実際に示します:
test_input = (1..5).map { |i| { created_at: i, some_val: rand(100) } }.shuffle
# => [{:created_at=>3, :some_val=>69},
# {:created_at=>5, :some_val=>15},
# {:created_at=>2, :some_val=>89},
# {:created_at=>4, :some_val=>77},
# {:created_at=>1, :some_val=>54}]
test_input.sort_by { |e| e[:created_at] }.to_podium
# => [{:created_at=>4, :some_val=>77},
# {:created_at=>2, :some_val=>89},
# {:created_at=>1, :some_val=>54},
# {:created_at=>3, :some_val=>69},
# {:created_at=>5, :some_val=>15}]