如何定義hash ,以及hash中經常使用的方法

和arr同樣,在初始化hash的時候須要注意一個問題,
好比拿空arr做爲一個默認值,這裏的空arr只生成了一個
object做爲默認值,在之後對於每個key,他的默認值都是一個引用指向這個object引用。
因此說若是經過了一個引用改變了這個object,則在之後定義任何key的時候,這個默認值都會改變。
好比對於另外任意一個key b來講,他的默認值已經改變成了1spa

一樣若是咱們針對每一個key都生成一個新的object做爲默認值,能夠用block {}code

 

 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的經常使用方法blog

 

 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 > 
相關文章
相關標籤/搜索