和arr一样,在初始化hash的时候需要注意一个问题,
比如拿空arr作为一个默认值,这里的空arr只生成了一个
object作为默认值,在以后对于每一个key,他的默认值都是一个引用指向这个object引用。
所以说如果通过了一个引用改变了这个object,则在以后定义任何key的时候,这个默认值都会改变。
比如对于另外任意一个key b来说,他的默认值已经改变成了1
同样如果我们针对每个key都生成一个新的object作为默认值,可以用block {}
1 soyo@soyo-ThinkPad-X1:~$ irb 2 2.4.1 :001 > h = Hash.new([]) 3 => {} 4 2.4.1 :002 > h[:a]<<1 5 => [1] 6 2.4.1 :003 > h[:b] 7 => [1] 8 2.4.1 :004 > h = Hash.new{|h,k|h[k]=[]} 9 => {} 10 2.4.1 :005 > h[:a]<<1 11 => [1] 12 2.4.1 :006 > h 13 => {:a=>[1]} 14 2.4.1 :007 > h[:b] 15 => [] 16 2.4.1 :008 > h = Hash.new {|h,k| h[k] = []} 17 => {} 18 2.4.1 :009 > h[:a] <<1 19 => [1] 20 2.4.1 :010 > h 21 => {:a=>[1]} 22 2.4.1 :011 > h[:b] 23 => []
hash的常用方法
1 soyo@soyo-ThinkPad-X1:~$ irb 2 2.4.1 :001 > h ={a:1,b:2} 3 => {:a=>1, :b=>2} 4 2.4.1 :002 > h[:c] =3 5 => 3 6 2.4.1 :003 > h 7 => {:a=>1, :b=>2, :c=>3} 8 2.4.1 :004 > h[:a] 9 => 1 10 2.4.1 :005 > h.delete(:a) 11 => 1 12 2.4.1 :006 > h 13 => {:b=>2, :c=>3} 14 2.4.1 :007 > h.assoc(:b) 15 => [:b, 2] 16 2.4.1 :008 > h.empty?() 17 => false 18 2.4.1 :009 > h.has_value?(2) 19 => true 20 2.4.1 :010 > h.has_key?(2) 21 => false 22 2.4.1 :011 > h.has_key?(:b) 23 => true 24 2.4.1 :012 > h.keys 25 => [:b, :c] 26 2.4.1 :013 > h.values 27 => [2, 3] 28 2.4.1 :014 > h.to_a 29 => [[:b, 2], [:c, 3]] 30 2.4.1 :015 > h2 ={d:4} 31 => {:d=>4} 32 2.4.1 :016 > h 33 => {:b=>2, :c=>3} 34 2.4.1 :017 > h.merge(h2) 35 => {:b=>2, :c=>3, :d=>4} 36 2.4.1 :018 > h 37 => {:b=>2, :c=>3} 38 2.4.1 :019 > h.each {|key,value| p [key,value]} 39 [:b, 2] 40 [:c, 3] 41 => {:b=>2, :c=>3} 42 2.4.1 :020 > h.each {|key| p key} 43 [:b, 2] 44 [:c, 3] 45 => {:b=>2, :c=>3} 46 2.4.1 :021 > h.each_value {|v|p v } 47 2 48 3 49 => {:b=>2, :c=>3} 50 2.4.1 :022 > h ={} 51 => {} 52 2.4.1 :023 > h[:z] =1 53 => 1 54 2.4.1 :024 > h[:a] = 2 55 => 2 56 2.4.1 :025 > h.each_key {|key| p key} 57 :z 58 :a 59 => {:z=>1, :a=>2} 60 2.4.1 :026 > h = {a:1,b:2} 61 => {:a=>1, :b=>2} 62 2.4.1 :027 > h.select {|key| key == :a} 63 => {:a=>1} 64 2.4.1 :028 > h 65 => {:a=>1, :b=>2} 66 2.4.1 :029 >