在Ruby中的讲台风格排序

Kyl*_*cot 11 ruby sorting ruby-on-rails

鉴于我有一系列哈希,我如何将它们(使用ruby)排序为讲台样式(使用其created_at值),如下图所示?

[
  { created_at: "DATETIME", src: "..." },
  { created_at: "DATETIME", src: "..." },
  { created_at: "DATETIME", src: "..." },
  { created_at: "DATETIME", src: "..." }
]
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

bon*_*nix 8

arr.sort_by{|a| a['created_at']}.inject([]){ |r, e| r.reverse << e }

有趣的问题!


agm*_*min 6

我相信你可以进一步压缩这个,但这样的事情可以解决这个问题:

# Your initial array
item_array = [{...}]
count = 0

# Sort it first, then stagger results to each side of the array
podium_sorted = item_array.sort_by{|a| a['created_at']}.inject([]) do |arr, item|
  count += 1
  count % 2 == 0 ? arr.unshift(item) : arr.push(item)
end
Run Code Online (Sandbox Code Playgroud)


Aar*_*nin 5

如果你不反对使用完全心理解决方案,我非常喜欢这个:

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]
Run Code Online (Sandbox Code Playgroud)

并将其展示在行动中:

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}]
Run Code Online (Sandbox Code Playgroud)