-3

鉴于此哈希:

myXML = {:_id=>BSON::ObjectId('51ad8d83a3d24b3b9f000001'),
         "Comment"=>nil,
         "Line"=>
          [{"LineNumber"=>"3.1",
            "Item"=>"fruit-004",
            "Description"=>"Peach",
            "Quantity"=>"1",
            "UnitCost"=>"1610",
            "DeclaredValue"=>"0",
            "PointValue"=>"13"},
           {"LineNumber"=>"8.1",
            "Item"=>"fruit-001",
            "Description"=>"Fruit Set",
            "Quantity"=>"1",
            "UnitCost"=>"23550",
            "PointValue"=>"105",
            "PickLine"=>
             [{"PickLineNumber"=>"8.1..1",
               "PickItem"=>"fruit-002",
               "PickDescription"=>"Apple",
               "PickQuantity"=>"1"},
              {"PickLineNumber"=>"8.1..2",
               "PickItem"=>"fruit-003",
               "PickDescription"=>"Orange",
               "PickQuantity"=>"2"}]}],
         "MemberId"=>"A00000001",
         "MemberName"=>"Bruce",
         "DeliveryId"=>"6377935",
         "ShipToAddress1"=>"123-4567",
         "OrderDate"=>"05/08/13",
         "Payments"=>
          [{"PayType"=>"Credit Card", "Amount"=>"1000"},
           {"PayType"=>"Points", "Amount"=>"5390"}]}

我可以使用具有nil代码价值的“评论”键删除键/值对:

myXML.each do |key, value|
  myXML.delete(key) if myXML[key] == nil
end

我相信有一个更好的方法可以用更少的 Ruby 代码来做到这一点。

4

1 回答 1

3

以下代码是否按您的预期工作?

myXML.delete_if{|key, value| value.nil?}

如果您打算递归删除,这当然不合适。

于 2013-06-05T01:07:15.897 回答