Restaurant = {:name=>"McDonalds",
:location=>"NYC",
:chefs=>
[{:name=>"Sunny", :food=>"fries"},
{:name=>"Brooklyn", :food=>"burgers"},
{:name=>"Mac", :food=>"burgers"}],
:waiters=>
[{:name=>"Jess", :role=>"senior manager"},
{:name=>"Sam", :role=>"manager"},
{:name=>"Jack", :role=>"server"},
{:name=>"Mary", :role=>"server"}]}
keys = Restaurant.map{|k,v| k if v.is_a? Array}.compact
keys.each{|i| Restaurant[i].each{|h| p h.keys,h.values}}
输出:
[:name, :food]
["Sunny", "fries"]
[:name, :food]
["Brooklyn", "burgers"]
[:name, :food]
["Mac", "burgers"]
[:name, :role]
["Jess", "senior manager"]
[:name, :role]
["Sam", "manager"]
[:name, :role]
["Jack", "server"]
[:name, :role]
["Mary", "server"]
keys.each{|i| Restaurant[i].each{|h| p h.to_a.flatten}}
输出:
[:name, "Sunny", :food, "fries"]
[:name, "Brooklyn", :food, "burgers"]
[:name, "Mac", :food, "burgers"]
[:name, "Jess", :role, "senior manager"]
[:name, "Sam", :role, "manager"]
[:name, "Jack", :role, "server"]
[:name, "Mary", :role, "server"]
keys.each{|i| Restaurant[i].each{|h| p h.to_a}}
输出
[[:name, "Sunny"], [:food, "fries"]]
[[:name, "Brooklyn"], [:food, "burgers"]]
[[:name, "Mac"], [:food, "burgers"]]
[[:name, "Jess"], [:role, "senior manager"]]
[[:name, "Sam"], [:role, "manager"]]
[[:name, "Jack"], [:role, "server"]]
[[:name, "Mary"], [:role, "server"]]
更新
需要'pp'
hsh = {:name=>"McDonalds",
:location=>"NYC",
:chefs=>
[{:name=>"Sunny", :food=>"fries"},
{:name=>"Brooklyn", :food=>"burgers"},
{:name=>"Mac", :food=>"burgers"}],
:waiters=>
[{:name=>"Jess", :role=>"senior manager"},
{:name=>"Sam", :role=>"manager"},
{:name=>"Jack", :role=>"server"},
{:name=>"Mary", :role=>"server"}]}
pp hsh.flat_map{|k,v| v.is_a?(Array) ? (v.flat_map(&:values)) : v }
输出
["McDonalds",
"NYC",
"Sunny",
"fries",
"Brooklyn",
"burgers",
"Mac",
"burgers",
"Jess",
"senior manager",
"Sam",
"manager",
"Jack",
"server",
"Mary",
"server"]
puts hsh.flat_map{|k,v| v.is_a?(Array) ? (v.flat_map(&:values)) : v }.join(",")
# => McDonalds,NYC,Sunny,fries,Brooklyn,burgers,Mac,burgers,Jess,senior manager,Sam,manager,Jack,server,Mary,server