Ruby-将具有数组值的Hash转换为哈希数组

时间:2019-05-20 23:59:19

标签: ruby

假设我有此哈希:

def aliases
  {
    blond: [
      'dark blond',
      'dirty blond',
      'honey blond',
      'sandy blond',
      'stawberry blond'
    ],
    brown: [
      'dark brown',
      'light brown'
    ],
    gray: [
      'grey'
    ]
  }
end

将其转换为以下内容的最优雅的方法是什么

[ { blond: 'dark blond' }, { blond: 'dirty blond' }, { brown: 'dark brown' } ... ]

1 个答案:

答案 0 :(得分:3)

aliases.flat_map { |k,v| v.map { |s| { k=>s } } }
  #=> [{:blond=>"dark blond"}, {:blond=>"dirty blond"}, {:blond=>"honey blond"},
  #    {:blond=>"sandy blond"}, {:blond=>"stawberry blond"}, {:brown=>"dark brown"},
  #    {:brown=>"light brown"}, {:gray=>"grey"}]