使用嵌套数组哈希红宝石

时间:2013-07-26 03:59:36

标签: ruby arrays nested hash

我在使用嵌套哈希时遇到了困难

 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"}]}

我如何删除杰克作为值的服务员哈希? 或者以服务器角色返回所有服务员的名字?

1 个答案:

答案 0 :(得分:2)

Restaurant[:waiters].reject!{|h| h[:name] == "Jack"}
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=>"Mary", :role=>"server"}]
}

Restaurant[:waiters].select{|h| h[:role] == "server"}
# => [{:name=>"Mary", :role=>"server"}]