我有一个Ruby数组,内容如下:
my_array
=> ["MPA5534285", "MPA5534555", "MPA553asdf5", "MPA553asdasdfasdfaf5"]
我有这样的Ruby哈希:
1.9.2p290 :012 > hash
=> {"MPA5534555"=>"something", "MPA553sf"=>"something", "MPA55345asdf5adfads"=>"something", "MPA553asdasdfasdfaf5"=>"something"}
我需要将数组与散列进行比较,并找到没有相应匹配的位置。
例如,在我的数组中,我有“MPA5534555”,如果我查看哈希,键确实存在。但是,在数组“MPA5534285”中没有哈希键。
我想要一个只有散列中没有键的数组。
答案 0 :(得分:6)
a = ["MPA5534285", "MPA5534555", "MPA553asdf5", "MPA553asdasdfasdfaf5"]
h = {"MPA5534555"=>"something", "MPA553sf"=>"something", "MPA55345asdf5adfads"=>"something", "MPA553asdasdfasdfaf5"=>"something"}
a - h.keys
# => ["MPA5534285", "MPA553asdf5"]
答案 1 :(得分:5)
这个变体比a - h.keys
稍快一点(无论如何都是在减去数组的情况下完成的,只是在这种情况下,h.keys
的重组不是必需的):
a.reject{ |e| h.has_key?(e) }
答案 2 :(得分:2)
看到解决方案如何快速比较,总是很有趣:
require 'benchmark'
my_array = ["MPA5534285", "MPA5534555", "MPA553asdf5", "MPA553asdasdfasdfaf5"]
hash = {
"MPA5534555" => "something",
"MPA553sf" => "something",
"MPA55345asdf5adfads" => "something",
"MPA553asdasdfasdfaf5" => "something"
}
n = 1_000_000
puts "For #{ n } loops:"
3.times do
Benchmark.bm(8) do |b|
b.report('keys') { n.times { my_array - hash.keys } }
b.report('has_key?') { n.times { my_array.reject{ |e| hash.has_key?(e) } } }
end
end
运行时输出:
ruby ~/Desktop/test.rb
For 1000000 loops:
user system total real
keys 3.910000 0.000000 3.910000 ( 3.908089)
has_key? 2.590000 0.000000 2.590000 ( 2.590154)
user system total real
keys 3.930000 0.010000 3.940000 ( 3.934498)
has_key? 2.580000 0.000000 2.580000 ( 2.583171)
user system total real
keys 3.940000 0.000000 3.940000 ( 3.936036)
has_key? 2.590000 0.000000 2.590000 ( 2.589483)