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

2.Array和Hash的创建对比:摘自《the ruby way》
8.1.1. Creating and Initializing an Array
The special Class methodclass 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.)
a = Array.[](1,2,3,4)
b = Array[1,2,3,4]
c = [1,2,3,4]


There is also a Class methodclass method called new that can take 0, 1, or 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:
d = Array.new # Create an empty array
e = Array.new(3) # [nil, nil, nil]
f = 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"]
g = 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 methodclass 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 methodclass 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.
d = Hash.new # Create an empty hash
e = Hash.new(99) # Create an empty hash
f = 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

1518

被折叠的 条评论
为什么被折叠?



