【问题标题】:dynamically add keys and values to hash and hash within hash动态添加键和值到散列和散列中的散列
【发布时间】:2016-05-27 03:19:14
【问题描述】:

我有一个名字数组

department = ['name1', 'name2', 'name3']

还有几个月的数组

month = ['jan', 'feb', 'mar', 'etc']

我需要将这些数组动态合并为哈希,如下所示:

h = {'name1' => {'jan' => '', 'feb' => '', 'mar' => '', 'etc' => ''},
'name2' => {'jan' => '', 'feb' => '', 'mar' => '', 'etc' => ''}, 'name3' => {'jan' => '', 'feb' => '', 'mar' => '', 'etc' => ''}}

我将如何动态地将键添加到我的哈希中?

【问题讨论】:

    标签: arrays ruby hash


    【解决方案1】:

    这是一种方法:

    department
      .each_with_object({}) do |name, h|
         # taking an empty hash which will be holding your final output.
         h[name] = month.product([""]).to_h
       end
    

    阅读Array#product 了解month.product([""]) 线路的工作原理。您可以使用to_h 将数组数组转换为哈希。

    【讨论】:

    • 这里Array#product的有趣用法。
    • 你和@tadman 都有非常有启发性的答案,谢谢 :)
    【解决方案2】:

    通常情况下,答案在于Enumerable 的力量:

    Hash[
      department.map do |d|
        [
          d,
          Hash[
            month.map do |m|
              [ m, '' ]
            end
          ]
        ]
      end
    ]
    

    这里发生了很多事情,但归结为一个两部分的过程,一个将department 列表转换为哈希哈希,第二部分使用转换后的month 结构填充它。

    Hash[] 是一种将键/值对转换为适当哈希结构的便捷方式。

    【讨论】:

      【解决方案3】:
      department = ['name1', 'name2', 'name3']
      month = ['jan', 'feb', 'mar', 'etc']
      
      month_hash = month.each_with_object({}) { |m, res| res[m] = '' }
      result = department.each_with_object({}) { |name, res| res[name] = month_hash.dup }
      
      p result
      

      这样你可以构建month_hash,然后用它来构建你需要的结果哈希

      【讨论】:

        【解决方案4】:

        我会这样做。

        1) 从你的月份数组中创建一个哈希

        month_hash = Hash[month.map { |m| [m ,''] }]
        

        2) 从部门数组中创建一个哈希,插入新创建的月份哈希。

        result_hash = Hash[department.map { |d| [d, month_hash] }]
        

        【讨论】:

          【解决方案5】:
          month = ['jan', 'feb', 'mar', 'etc']
          department = ['name1', 'name2', 'name3']
          
          month_hash = month.map {|m| [m, '']}.to_h
          p department.map {|d| [d, month_hash]}.to_h
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-03-13
            • 1970-01-01
            • 2012-08-03
            • 2011-02-27
            • 2015-09-12
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多