【问题标题】:Converting Ruby array of array into a hash将数组的Ruby数组转换为哈希
【发布时间】:2021-11-25 16:40:03
【问题描述】:

我有一个数组如下:

[
  ["2021-07-26T11:38:42.000+09:00", 1127167],
  ["2021-08-26T11:38:42.000+09:00", 1127170],
  ["2021-09-26T11:38:42.000+09:00", 1127161],
  ["2021-07-25T11:38:42.000+09:00", 1127177],
  ["2021-08-27T11:38:42.000+09:00", 1127104]
]

我想要的输出:

{
  "2021-July" => [["2021-07-26T11:38:42.000+09:00", 1127167],["2021-07-25T11:38:42.000+09:00", 1127177]], 
  "2021-August" => [["2021-08-26T11:38:42.000+09:00", 112717],["2021-08-27T11:38:42.000+09:00", 112710]],  
  "2021-September" => ["2021-09-26T11:38:42.000+09:00", 112716]
}

我想根据每个数组元素中的日期值创建哈希键year-month 格式。最简单的方法是什么?

【问题讨论】:

    标签: arrays ruby-on-rails hash


    【解决方案1】:

    使用group_by

    date_array = [["2021-07-26T11:38:42.000+09:00", 1127167],["2021-08-26T11:38:42.000+09:00", 112717],["2021-09-26T11:38:42.000+09:00", 112716],["2021-07-25T11:38:42.000+09:00", 1127177],["2021-08-27T11:38:42.000+09:00", 112710]]
    result = date_array.group_by{ |e| Date.parse(e.first).strftime("%Y-%B") }
    

    【讨论】:

      【解决方案2】:
      date_array = [["2021-07-26T11:38:42.000+09:00", 1127167],["2021-08-26T11:38:42.000+09:00", 112717],["2021-09-26T11:38:42.000+09:00", 112716],["2021-07-25T11:38:42.000+09:00", 1127177],["2021-08-27T11:38:42.000+09:00", 112710]]
      
      result_date_hash = Hash.new([])
      
      date_array.each do |date|
        formatted_date = Date.parse(date.first).strftime("%Y-%B")
        result_date_hash[formatted_date] += date
      end
      

      输出:

      puts result_date_hash 
       => 
      {"2021-July"=>["2021-07-26T11:38:42.000+09:00", 1127167, "2021-07-25T11:38:42.000+09:00", 1127177],
       "2021-August"=>["2021-08-26T11:38:42.000+09:00", 1127170, "2021-08-27T11:38:42.000+09:00", 1127104],
       "2021-September"=>["2021-09-26T11:38:42.000+09:00", 1127161]} 
      

      【讨论】:

      • 看起来可以通过group_by one-liner 实现
      • 小心,result_date_hash = Hash.new([]) 几乎从来都不是您想要的,它只在这里有效,因为您使用a += e 将元素添加到数组中并且+= 复制了a。你真的应该说result_date_hash = Hash.new { |h, k| h[k] = [] }
      猜你喜欢
      • 2021-10-16
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      相关资源
      最近更新 更多