【问题标题】:Sorting Ruby Array of hashes with 2 date keys使用 2 个日期键对 Ruby 哈希数组进行排序
【发布时间】:2021-02-18 08:41:27
【问题描述】:

我有一个哈希数组,其中包含 2 个具有时间戳值 (YYYY/MM/DD/HH/MM/SS) 的键:start_dateend_date

Array_initial = [
    { :started_at => 20201105143200, :ended_at => 20201105143900 },
    { :started_at => 20201105142900, :ended_at => 20201105143300 },
    { :started_at => 20201105142800, :ended_at => 20201105143000 },
]

我想将此哈希数组转换为数组数组,但通过比较 started_atended_at 时间戳进行排序。所以结果是这样的:

Array_final = [
[:started_at, 20201105142800], 
[:started_at, 20201105142900], 
[:ended_at, 20201105143000], 
[:started_at, 20201105143200], 
[:ended_at, 20201105143300], 
[:ended_at, 20201105143900]
]

不知道怎么做...

【问题讨论】:

    标签: arrays ruby sorting ruby-hash


    【解决方案1】:

    首先你要改变结构:

    a = [
      { :started_at => 20201105143200, :ended_at => 20201105143900 },
      { :started_at => 20201105142900, :ended_at => 20201105143300 },
      { :started_at => 20201105142800, :ended_at => 20201105143000 },
    ]
    

    到与你的结果结构相匹配的东西:

    [
      [key, timestamp],
      [key, timestamp],
      ...
    ]
    

    以便您对其进行排序。

    Enumerable#flat_mapHash#to_a 会很好地做到这一点:

    a.flat_map(&:to_a)
    # [
    #   [:started_at, 20201105143200],
    #   [:ended_at,   20201105143900],
    #   [:started_at, 20201105142900],
    #   [:ended_at,   20201105143300],
    #   [:started_at, 20201105142800],
    #   [:ended_at,   20201105143000]
    # ]
    

    然后sort by last 元素就完成了:

    a.flat_map(&:to_a).sort_by(&:last)
    # [
    #   [:started_at, 20201105142800],
    #   [:started_at, 20201105142900],
    #   [:ended_at,   20201105143000],
    #   [:started_at, 20201105143200],
    #   [:ended_at,   20201105143300],
    #   [:ended_at,   20201105143900]
    # ]
    

    【讨论】:

    • 感谢您快速而完美的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2015-11-07
    相关资源
    最近更新 更多