将对象推入循环内的哈希

时间:2019-03-05 04:40:01

标签: ruby hash

我正在尝试实现以下JSON结果:

$windowsTimeZone = 'Pacific Standard Time';

$ianaTimeZone = $microsoftWindowsTimeZones[$windowsTimeZone];

使用JavaScript,我将遍历结果并执行以下操作:

 {
    "movie" =>
             [{
               "title": "Thor",
               "year" : 2011,
             },
             {
               "title": "Iron Man",
               "year" : 2008,
             }],
     "tv" =>  
             [{
               "title": "Parks and Recreation"
               "year": 2009
             },
             {
               "title": "Friends"
               "year": 1994
             }]
  }

使用Ruby代码,我走得最远的是:

results['movie'].push(item);
results['tv'].push(item);

我在这里想念什么?

3 个答案:

答案 0 :(得分:1)

我认为您可以通过使用Enumerable#each_with_object并为哈希分配默认值来获得所需的内容。

def group_search_results(items)
  results = Hash.new { |hash, key| hash[key] = [] }
  items.each_with_object(results) do |item|
    results[item['Type']] << {'title' => item['Title'], 'year' => item['Year']}
  end
end

describe "search_results" do
  it "groups into an object" do
    items = [
      {'Type' => 'movie', 'Title' => 'Thor', 'Year' => 2011},
      {'Type' => 'movie', 'Title' => 'Iron Man', 'Year' => 2008},
      {'Type' => 'series', 'Title' => 'Parks and Recreation', 'Year' => 2009},
      {'Type' => 'series', 'Title' => 'Friends', 'Year' => 1994},
    ]

    results = group_search_results(items)
    expect(results).to eq({
      'movie' => [
        {'title' => 'Thor', 'year' => 2011},
        {'title' => 'Iron Man', 'year' => 2008},
      ],
      'series' => [
        {'title' => 'Parks and Recreation', 'year' => 2009},
        {'title' => 'Friends', 'year' => 1994},
      ],
    })
  end
end

答案 1 :(得分:0)

我认为问题与哈希的初始化有关。 movietv键当前不是数组。您可以像这样初始化哈希:

@results = { 'movie' => [], 'tv' => [] }

其他代码的外观如下:

@results = { 'movie' => [], 'tv' => [] }
results['Search'].each do |r|
  if r['Type'] == 'movie'
    @results['movie'] << {
        'title' => r['Title'],
        'year' => r['Year']
    }
  elsif r['Type'] == 'series'
    @results['tv'] << {
        'title' => r['Title'],
        'year' => r['Year']
    }
  end
end 

答案 2 :(得分:0)

results =  { 
  search: { 
    movie: [
      { title: 'Thor', year: 2011 },
      { title: 'Iron Man', year: 2008 },
    ],
    tv: [
      { title: 'Parks and Recreation', year: 2009 },
      { title: 'Friends', year: 1994 },
    ]
  }
}

@results = Hash.new{|k, v| k[v] = []}
results[:search].each do |type, array| 
  @results[type].push(*array) 
end

results[:search].each_with_object(Hash.new{|k, v| k[v] = []}) do |(type, array), hash| 
  hash[type].push(*array) 
end