开发者

See if a key in one hash does not exist in another hash?

What's a fast (or even fastest?) way of 开发者_运维技巧seeing if there is a key in one Ruby hash that doesn't exist in another? I'm assuming a hash is the most efficient data structure to do this with, but I'm open for anything such as putting things in a Set also.


a = { :a => 1, :b => 2 , :v => 3}
b = { :a => 3, :b => 22 , :g => 3}
a.keys - b.keys
#=> [:v]
b.keys - a.keys
#=> [:g]


A simple way is something like:

hash1.keys - hash2.keys

Your result is the keys in hash1 that aren't in hash2


@fl00r's answer is what I would personally write, as it's fast for me (the coder). However, since you asked for "fast", and might have meant "fast for the computer", you should be aware that each time you call this it has to walk both sets of keys fully.

If you need to do this frequently, and you really only care if there is any key that might be missing, you might do something like:

def same_keys?( a, b )
  a.length == b.length && a.keys.all?{ |k| b.key?(k) }
end

You get an early out if there aren't the same number of keys, and you get an early out as soon as it finds any key not present in the other. Unlike the more powerful answer using array set mathematics, you don't find out how many keys, or which keys, are present in one hash but not the other.

Note: I have not benchmarked the above to show that it will be faster. Given that the array math is implemented in C, it is possible that calling all? and invoking the key? method for all keys may be slower than getting the full array of differences for many hashes that you care about.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜