比较两个哈希值,如果ID不存在则删除

时间:2011-08-26 09:09:53

标签: ruby hash compare

我有两个哈希,一个看起来像这样:

{:id => "SG_5viWPcG0SLvszXbBxogLkT_51.514568_-0.126244@1300740367",
 :name => "Shellys Shoes",
 :lat => 51.5145683289,
 :lng => -0.1262439936}

这只是一条记录,大约有80条,

我的第二个哈希是:

{"id":"SG_2zNWLdG9147g2ROvNWpDHr_51.512360_0.124480@1300740823",
"lat":51.5123596191,
"lng":-0.1244800016}

上面的哈希只是一条记录,但它是经过一个不返回所有记录的API后面的HASH的产品,只有有效的记录,我想要做的是比较顶部哈希与底部的一个并删除底部哈希中不存在的任何记录,

例如,如果id:SG_5viWPcG0SLvszXbBxogLkT_51.514568_-0.126244@1300740367不在第二个哈希中,则删除该记录,

我可以比较哈希值,但是如果ID不存在则无法看到如何删除?

谢谢你们!

编辑: 这些是返回的值......

{"points":[{"id":"SG_75oKOgvgFPLjwmdyAKA2rq_51.512825_-0.124655@1300740283","lat":51.5128250122,"lng":-0.1246550009},{"id":"SG_0Sz9CBF5t70tdAffTKYNSg_51.512360_-0.124388@1300740807","lat":51.5123596191,"lng":-0.1243880019},{"id":"SG_2zNWLdG9147g2ROvNWpDHr_51.512360_-0.124480@1300740823","lat":51.5123596191,"lng":-0.1244800016},{"id":"SG_5PvBx89sLPgplapegVJDFv_51.513100_-0.124809@1300740049","lat":51.5130996704,"lng":-0.1248089969},{"id":"SG_4luyHFi5R2f1w3cpjT61ik_51.513393_-0.124556@1300740719","lat":51.5133934021,"lng":-0.1245559976},{"id":"SG_4luyHFi5R2f1w3cpjT61ik_51.513393_-0.124556@1300740719","lat":51.5133934021,"lng":-0.1245559976},{"id":"SG_0pEvrpt7bs42jPAxFSrquC_51.512264_-0.124413@1300740807","lat":51.5122642517,"lng":-0.1244129986},]}

这是原始格式:

[ {         :id => "SG_2Km6LX3tEcFwx24eotTHIY_51.513016_-0.123721@1300740411",
            :name => "French Connection Group Plc",
             :lat => 51.5130157471,
             :lng => -0.1237210035
}]

1 个答案:

答案 0 :(得分:0)

您可以从返回的值中收集有效ID的列表,例如:

valid_ids = returned["points"].collect { |point| point["id"] }

然后,您可以使用以下内容从原始文件中删除无效值:

original.delete_if { |entry| !valid_ids.include? entry[:id] }