2012-02-10 50 views
1

我有一個Ruby的數組內容是這樣的:如何比較Ruby數組和哈希的內容?

my_array 
=> ["MPA5534285", "MPA5534555", "MPA553asdf5", "MPA553asdasdfasdfaf5"] 

我有一個Ruby的哈希值是這樣的:

1.9.2p290 :012 > hash 
=> {"MPA5534555"=>"something", "MPA553sf"=>"something", "MPA55345asdf5adfads"=>"something", "MPA553asdasdfasdfaf5"=>"something"} 

我需要數組的哈希比較,發現那裏沒有相應的匹配。

例如,在我的數組中,我有「MPA5534555」,如果我查看哈希,密鑰確實存在。但是,在陣列中「MPA5534285」在散列中沒有密鑰。我想要一個數組,只有在哈希中沒有鍵的數組。

回答

6
a = ["MPA5534285", "MPA5534555", "MPA553asdf5", "MPA553asdasdfasdfaf5"] 

h = {"MPA5534555"=>"something", "MPA553sf"=>"something", "MPA55345asdf5adfads"=>"something", "MPA553asdasdfasdfaf5"=>"something"} 


a - h.keys 
# => ["MPA5534285", "MPA553asdf5"] 
5

這種變體是一點點比a - h.keys快(它反正減去陣列時,幕後完成,只有在h.keys這種情況下換湯不換藥不是nesessary):

a.reject{ |e| h.has_key?(e) } 
2

它總是有趣的看到解決方案如何比較speedwise:

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)