我正在尝试实现以下JSON结果:
{ “movie”=> [{ “标题”:“雷神”, “年”:2011年, }, { ” …
我认为问题与哈希的初始化有关。该 movie 和 tv 键目前不是数组。您可以像这样初始化哈希:
movie
tv
@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
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
我想你可以通过使用获得你想要的东西 Enumerable#each_with_object 并为哈希值分配默认值。
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