ruby Hash

 1. Array是一种特殊的Hash,Array的索引恰为它的键

 2.Array和Hash的创建对比:摘自《the ruby way》

  

8.1.1. Creating and Initializing an Array
The special 
class method [] is used to create an array; the data items listed in the brackets are used to populate the array. The three ways of calling this method are shown in the following lines. (Arrays a, b, and c will all be populated identically.)

= Array.[](1,2,3,4
)
= Array[1,2,3,4
]
= [1,2,3,4
]


There 
is also a 
class method called new that can take 01or 2 parameters. The first parameter is the initial size of the array (number of elements). The second parameter is the initial value of each of the elements:

=
 Array.new               # Create an empty array
= Array.new(3
)            # [nil, nil, nil]
= Array.new(3"blah")    # ["blah""blah""blah"
]


Look carefully at the last line 
of this preceding example. A common "beginner's error" is to think that the objects in the array are distinct. Actually, they are three references to the same object. Therefore if you change that object (as opposed to replacing it with another object), you will change all elements of the array. To avoid this behavior, use a block. Then that block is evaluated once for each element, and
 all elements are different objects:

f[
0].capitalize!            # f is now: ["Blah""Blah""Blah"
]
= Array.new(3) { "blah" } # ["blah""blah""blah"
]
g[
0].capitalize!            # g is now: ["Blah""blah""blah"
]

 

 

8.2.1. Creating a New Hash
As with Array, the special 
class method [] is used to create a hash. The data items listed in the brackets are used to form the mapping of the hash.

Six ways 
of
 calling this method are shown here. (Hashes a1 through c2 will all be populated identically.)

a1 
= Hash.[]("flat",3,"curved",2
)
a2 
= Hash.[]("flat"=>3,"curved"=>2
)
b1 
= Hash["flat",3,"curved",2
]
b2 
= Hash["flat"=>3,"curved"=>2
]
c1 
= {"flat",3,"curved",2
}
c2 
= {"flat"=>3,"curved"=>2
}
For a1, b1, and
 c1: There must be
# an even number 
of
 elements.


There 
is also a 
class method called new that can take a parameter specifying a default value. Note that this default value is not actually part of the hash; it is simply a value returned in place of nil.

=
 Hash.new         # Create an empty hash
= Hash.new(99
)     # Create an empty hash
= Hash.new("a"=>3
) # Create an empty hash
e[
"angled"]          # 99

e.inspect            # {}
f[
"b"]               # {"a"=>3} (default value is
                     #   actually a hash itself)
f.inspect            # {}

 

Hash中的逗号可起到=>的效果,成对当成一对键值对。

3.Hash中的迭代器

4.sort the Hash

 

symbol键不具有可对比性,字符串具有,因此可以排序

4.Hash与Array的相互转换:

  Hash.to_a  hash转为array

 Hash[*array]  array转为hash

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值