如果您不反对使用完全精神的解决方案,我非常喜欢这个:
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}]