从嵌套数组创建嵌套哈希

时间:2018-12-07 10:39:14

标签: ruby-on-rails arrays ruby hash

我想从以下查询中获取答复:

sites = Site.find(request.review_sites).pluck(:id, :location_id, :site_name, :review_url,:created_at)

提供了如下所示的输出,

[
  [
    50,
    2,
    "google",
    "https://search.google.com/local/writereview?placeid=000000001flMRNRVr8YpJWuY",
    Thu, 06 Dec 2018 20:18:29 UTC +00:00
  ],
  [
    51,
    2,
    "facebook",
    "https://www.facebook.com/biz/reviews/?ref=page_internal",
    Thu, 06 Dec 2018 20:18:35 UTC +00:00
  ]
]

放入嵌套的哈希,如下所示(稍后将以JSON形式使用):

{
  :google => {
    :id => 50,
    :create_at => "2018-12-06T20:18:29.651Z",
    :site_name => "google",
    :review_url => "https://search.google.com/local/writereview?placeid=00000000001flMRNRVr8YpJWuY",
    :location_id => 2
  },
  :facebook => {
    :id => 51,
    :create_at => "2018-12-06T20:18:35.639Z",
    :site_name => "facebook",
    :review_url => "https://www.facebook.com/biz/reviews/?ref=page_internal",
    :location_id => 2
  }
}

我意识到这是重复的,但是我正在努力实现给出的一些答案。我正在努力以编程方式执行此操作,因此将不胜感激。

4 个答案:

答案 0 :(得分:2)

让您的数组为array。在Ruby <2.6中,您可以通过以下方式获取哈希值:

array.map do
  |id, location_id, site_name, review_url, create_at|
  [site_name.to_i, {
    id: id,
    create_at: create_at,
    site_name: site_name,
    review_url: review_url,
    location_id: location_id,
  }].to_h
end

在Ruby 2.6中,您可以通过以下方式获得它:

array.to_h do
  |id, location_id, site_name, review_url, create_at|
  [site_name.to_i, {
    id: id,
    create_at: create_at,
    site_name: site_name,
    review_url: review_url,
    location_id: location_id,
  }]
end

答案 1 :(得分:1)

在您的情况下,pluck可能不是适合该工作的工具。

如果您可以控制它,我将其更改为以下内容(为方便起见,将其分成几行)。

collection = Site.find(request.review_sites)
columns = [:id, :location_id, :site_name, :review_url, :created_at]
sites = collection.select(columns).map { |v| [v.id, v.attributes] }.to_h

使用select将所需的属性作为哈希值返回,然后可以根据需要映射它。那么,转换为json就是sites.to_json的问题。

答案 2 :(得分:1)

我找到了你想要的东西,

尝试跟随,

MessageQueue

输出看起来像

sites = Site.find(request.review_sites)
          .as_json(only: [:id, :location_id, :site_name, :review_url,:created_at])
          .group_by { |x| x['site_name'] }

答案 3 :(得分:0)

由于@dcarneiro的response,我得以解决

这是我为发现它的任何人从嵌套数组中创建嵌套哈希的方法。

      review_sites = Site.find(request.review_sites).pluck(:id, :location_id, :site_name, :review_url,:created_at)
      sites_hash = Hash[review_sites.map do |site| 
        [site[2], Hash['id', site[0], 'location_id', site[1], 'site_name', site[2], 'review_url', site[3], 'create_at', site[4] ]]
      end]