.flatten
ここは便利かも。構造にこだわらない場合は、反復する前に平坦化するだけで、深さの変化について心配する必要はありません。
1.9.3p194 :001 > root = [{"sku"=>"reprint"}, [], nil, {"quantity"=>"1"}, [], nil, {"shippingOptions"=>"PQRS"},
1.9.3p194 :002 > [{"option"=>"PQRS"}], nil, {"abc"=>"abcccc"},
1.9.3p194 :003 > [], nil,{"sku"=>"poster"},
1.9.3p194 :004 > [], nil, {"quantity"=>"2"}, [], nil, {"shippingOptions"=>"MNLIJK"},
1.9.3p194 :005 > [{"option"=>"MNL"}, {"option"=>"IJK"}], nil, {"sku"=>"cards"},
1.9.3p194 :006 > [], nil, {"quantity"=>"5"},
1.9.3p194 :007 > [], nil, {"shippingOptions"=>"DEFABC"}, [{"option"=>"DEF"}, {"option"=>"ABC"}], nil]
=> [{"sku"=>"reprint"}, [], nil, {"quantity"=>"1"}, [], nil, {"shippingOptions"=>"PQRS"}, [{"option"=>"PQRS"}], nil, {"abc"=>"abcccc"}, [], nil, {"sku"=>"poster"}, [], nil, {"quantity"=>"2"}, [], nil, {"shippingOptions"=>"MNLIJK"}, [{"option"=>"MNL"}, {"option"=>"IJK"}], nil, {"sku"=>"cards"}, [], nil, {"quantity"=>"5"}, [], nil, {"shippingOptions"=>"DEFABC"}, [{"option"=>"DEF"}, {"option"=>"ABC"}], nil]
1.9.3p194 :008 > root.flatten!
=> [{"sku"=>"reprint"}, nil, {"quantity"=>"1"}, nil, {"shippingOptions"=>"PQRS"}, {"option"=>"PQRS"}, nil, {"abc"=>"abcccc"}, nil, {"sku"=>"poster"}, nil, {"quantity"=>"2"}, nil, {"shippingOptions"=>"MNLIJK"}, {"option"=>"MNL"}, {"option"=>"IJK"}, nil, {"sku"=>"cards"}, nil, {"quantity"=>"5"}, nil, {"shippingOptions"=>"DEFABC"}, {"option"=>"DEF"}, {"option"=>"ABC"}, nil]
1.9.3p194 :011 > root.each do |r|
1.9.3p194 :012 > next if r.nil?
1.9.3p194 :013?> puts r.to_s
1.9.3p194 :014?> end
{"sku"=>"reprint"}
{"quantity"=>"1"}
{"shippingOptions"=>"PQRS"}
{"option"=>"PQRS"}
{"abc"=>"abcccc"}
{"sku"=>"poster"}
{"quantity"=>"2"}
{"shippingOptions"=>"MNLIJK"}
{"option"=>"MNL"}
{"option"=>"IJK"}
{"sku"=>"cards"}
{"quantity"=>"5"}
{"shippingOptions"=>"DEFABC"}
{"option"=>"DEF"}
{"option"=>"ABC"}
RE: コメント。
data = [{"sku"=>"reprint"}, [], nil, {"quantity"=>"1"}, [], nil, {"shippingOptions"=>"PQRS"}, [{"option"=>"PQRS"}], nil, {"abc"=>"abcccc"}, [], nil, {"sku"=>"poster"}, [], nil, {"quantity"=>"2"}, [], nil, {"shippingOptions"=>"MNLIJK"}, [{"option"=>"MNL"}, {"option"=>"IJK"}], nil, {"sku"=>"cards"}, [], nil, {"quantity"=>"5"}, [], nil, {"shippingOptions"=>"DEFABC"}, [{"option"=>"DEF"}, {"option"=>"ABC"}], nil]
hash_collection = data.flatten.map(&:to_a).flatten(1).reduce({}) { |h,(k,v)| (h[k] ||= []) << v; h}
生成:
=> {"sku"=>["reprint", "poster", "cards"], "quantity"=>["1", "2", "5"], "shippingOptions"=>["PQRS", "MNLIJK", "DEFABC"], "option"=>["PQRS", "MNL", "IJK", "DEF", "ABC"], "abc"=>["abcccc"]}
私は実際に新しいデータを次のようにしたいと思っています:
{{"sku"=>"Reprint"},{"quantity"=>"1"},{"option"=>"PQRS"}}
{{"sku"=>"Poster"},{"quantity"=>"2"},{"option"=>"MNL"},{"option"=>"IJK"}}
{{"sku"=>"Cards"}, {"quantity"=>"5"},{"option"=>"DEF"},{"option"=>"ABC"}}
{{"sku"=>"Books"},{"quantity"=>"6"},{"option"=>"QIU"},{"option"=>"PSJ"}, option"=>"IQA"},{"suboption"=>"ikh"},{"subsuboption"=>"uuuuuuuuuuuuuuuuu"}}