1.创建哈希:就像创建数组一样,我们可以通过Hash类来创建一个Hash实例:
1
2
|
h1 =
Hash
.
new
#默认值为nil
h2 =
Hash
.
new
(“This is my first hash instance”)
#默认值为” This is my first hash instance”:
|
上面两个例子都创建了一个空的Hash实例。一个Hash对象总是有一个默认的值——因为如果在一个Hash对象里没有找到指定的索引(key),将会返回默认值。
创建了Hash对象后,我们就可以像数组那样给他添加/删除项了。唯一不同的是,在数组中的索引只是能整数,而在Hash中索引(key)可以是任何类型(any type of object)且唯一的数据:
1
2
3
4
|
h2[
"one"
] =
"北京"
h2[
"two"
] =
"上海"
h2[
"three"
] =
"深圳"
h2[
"four"
] =
"广州"
|
Note: 如果在给Hash赋值时,使用的相同的key,那么后面的值会覆盖掉前面的值。另外,Ruby还提供了一种方便的创建和初始化Hash的方法,只需要在key后面加一个=>符号并跟一个值即可。每个key-value对用逗号隔开。然后整体用大括号括起来:
1
2
3
4
5
6
|
h2 = {
"one"
=>
"北京"
,
"two"
=>
"上海"
,
"three"
=>
"深圳"
,
"four"
=>
"广州"
}
|
2.通过索引存取Hash的值:
要想获取某个值,可以用下面的方法:
1
|
puts h2[“one”]
#=>”北京”
|
如果指定的key不存在,将返回默认的值(前面有提到过)。此外,我们还可以用default方法获取默认值,用default+=方法设置默认值
1
2
|
puts h1.default
h1.default += “This is set value method”
|
3.复制Hash:
和数组一样,我们可以把一个Hash变量分配给另一个hash变量,它们都引用想同的Hash,所以如果其中一个的值变了,那么另外一个的值也会跟着变:
1
2
3
|
h3 = h2
h3[“one”] = “西安”
puts h h2[“one”]
#=>”西安”
|
有的时候我们不希望上面的情况发生,即:修改了其中一个的值另一个也跟着修改了,我们可以使用clone方法make a new copy
1
2
3
|
h4 = h2.clone
h4[“one”] = “大连”
puts h2[“one”]
#=>”西安”(i.e. 值没有修改)
|
4.Hash排序:
当我们需要对Hash进行排序时,不能像数组那样简单的使用sort方法,因为数组中的数据类型都是一样的(整型),Hash中的数据类型可能并不完全一样,如整数类型和字符串类型就没法一起排序,此时就需要我们进行处理,如下(如果Hash中的数据类型全部相同可以不进行如下处理):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
def
sorted_hash(aHash)
return
aHash.sort{
|a,b| a.to_s <=> b.to_s
}
End
h1 = {
1
=>
'one'
,
2
=>
'two'
,
3
=>
'three'
}
h2 = {
6
=>
'six'
,
5
=>
'five'
,
4
=>
'four'
}
h3 = {
'one'
=>
'A'
,
'two'
=>
'B'
,
'three'
=>
'C'
}
h4 = h1.merge(h2)
#合并hash
h5 = h1.merge(h3)
def
sorted_hash(aHash)
return
aHash.sort{|a,b| a.to_s <=> b.to_s }
end
p(h4)
p(h4.sort)
p(h5)
p(sorted_hash(h5))
|
结果
1
2
3
4
|
{5=>"five", 6=>"six", 1=>"one", 2=>"two", 3=>"three", 4=>"four"}
[[1, "one"], [2, "two"], [3, "three"], [4, "four"], [5, "five"], [6, "six"]]
{"two"=>"B", "three"=>"C", 1=>"one", 2=>"two", "one"=>"A", 3=>"three"}
[[1, "one"], [2, "two"], [3, "three"], ["one", "A"], ["three", "C"], ["two", "B"]]
|
事实上Hash的sort方法是把一个Hash对象转换成以[key,value]为单个元素的一个数组,然后再用数组的sort方法进行排序。
5.Hash类常用方法:
方法 | 说明 |
size() | 返回Hash对象的长度 |
length() | 返回Hash对象的长度 |
include?(key) | 判断指定的Hash对象是否包含指定的key |
has_key?(key) | 判断指定的Hash对象是否包含指定的key |
delete(key) | 删除Hash对象中指定key的对应元素 |
keys() | 返回由Hash对象中全部key组成的数组 |
values() | 返回由Hash对象中全部value组成的数组 |
e.g.
1
2
3
4
5
6
7
8
9
10
11
12
|
student = {
"name"
=>
"Steve"
,
"age"
=>
22
,
"Gender"
=>
"male"
}
p student.keys
#=> ["name", "Gender", "age"]
p student.values
#=> ["Steve", "male", 22]
puts student.include?(
"age"
)
#=> true
puts student.size
#=> 3
student.delete(
"Gender"
)
puts student.has_key?(
"Gender"
)
#=>false
puts student.size
#=>2
|
6.Hash的转换使用
在处理嵌套了几层的hash时,总是感觉很混乱,读取、修改时都很麻烦。因此想到把hash转换为对象,直接生成key的get/set方法,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
class
HashObj
class
<<
self
def
load_from_hash(hash)
if
hash.instance_of?
Hash
obj = HashObj.
new
hash.
each
{|k,v| obj.send
:def_sget_method
,k,HashObj.load_from_hash(v)}
obj
elsif
hash.instance_of?
Array
hash.map{|m| HashObj.load_from_hash(m) }
else
hash
end
end
end
def
attributes
hash = {}
@@reg
||= /=/
self
.singleton_methods.reject{|x|
@@reg
=~ x.to_s}.
each
do
|m|
v =
self
.send(m)
if
v.instance_of? HashObj
real_v = v.attributes
elsif
v.instance_of?
Array
real_v = []
v.
each
do
|l|
if
l.instance_of? HashObj
real_v << l.attributes
else
real_v << l
end
end
else
real_v = v
end
hash[m] = real_v
end
hash
end
protected
def
def_sget_method(name,val)
self
.instance_variable_set
"@#{name}"
,val
self
.define_singleton_method
"#{name}="
do
|n_val|
instance_variable_set
"@#{name}"
,n_val
end
self
.define_singleton_method name
do
instance_variable_get
"@#{name}"
end
end
end
|
使用demo
1
2
3
4
5
6
7
8
9
10
11
12
|
hash = {name:
'jack'
,age:
22
,phone:[
'61900871'
,
'8787876'
],
basic_info:{country:
'USA'
,city:
'New York'
}}
obj = HashObj.load_from_hash hash
obj.name
#'jack'
obj.age
#22
obj.phone
#['61900871','8787876']
obj.basic_info
#<HashObj:0x007f9eda02b360 @country="USA", @city="New York">
obj.basic_info.country
#'USA'
obj.attributes == hash
#true
obj.age =
30
obj.attributes
#{:name=>"jack", :age=>30, :phone=>["61900871", "8787876"],
# :basic_info=>{:country=>"USA", :city=>"New York"}}
|