ruby - 数组group_by子元素

时间:2017-09-19 08:47:43

标签: ruby

我需要通过数组元素对这个YAML结构进行分组。

这是我的YAML结构的例子:

articles:
  - title: 'Title 1'
    url: 'https://example.com'
    data: July 21, 2017
    categories:
      - 'category 1'
      - 'category 2'
  - title: 'Title 2'
    url: 'https://example.com'
    data: July 23, 2017
    categories:
      - 'category 2'

我需要的结果是这个或类似的:

['category 1' => 
    [
        {title: 'Title 1', url: 'https://example.com', data: July 21, 2017, categories: ['category 1', 'category 2']}
    ], 
    'category 2' => [
        {title: 'Title 1', url: 'https://example.com', data: July 21, 2017, categories: ['category 1', 'category 2']},
        {title: 'Title 2', url: 'https://example.com', data: July 23, 2017, categories: ['category 2']}
    ]
]
你能帮帮我吗?提前谢谢

更新

我试过这个:

articles.group_by(&:categories).map{|v, a| [v, a] }

但关键不是单一类别,而是类别元素。我想我需要一个更多的循环,但经过一些试验后我还没有得到结果。

对不起,但我是ruby的新手

更新2: 错误的结果是:

[
  [
    [
      "category 1",
      "category 2"
    ],
    [
      {
        "title": "Title 1",
        "url": "https://example.com",
        "data": "July 21, 2017",
        "categories": [
          "category 1",
          "category 2"
        ]
      }
    ]
  ],
  [
    [
      "category 2"
    ],
    [
      {
        "title": "Title 2",
        "url": "https://example.com",
        "data": "July 23, 2017",
        "categories": [
          "category 2"
        ]
      }
    ]
  ]
]

2 个答案:

答案 0 :(得分:2)

在这种情况下,看起来普通的优质减速机可以更好地满足您的需求:

articles.each_with_object({}) do |article, acc|
  acc.merge! article.categories.map { |c| [c, article] }.to_h
end

甚至:

articles.map do |article|
  article.categories.map { |c| [c, article] }.to_h
end.reduce(&:merge)

答案 1 :(得分:1)

你需要一个group_by吗?为什么不是一个简单的嵌套循环?

result = {}
articels.each do |article|
  article.categories.each do |cat|
    result[cat] ||= []
    result[cat] << article
  end
end