- 数组
数组
Arrays
数组
You can create an array by listing some items within square brackets ([]) and separating them with commas. Ruby’s arrays can accomodate diverse object types.
您可以通过在方括号中列出一些以逗号分隔的项来创建数组。
ruby> ary = [1, 2, "3"]
[1, 2, "3"]
Arrays can be concatenated or repeated just as strings can.
数组可以同字符串一样被连接或重复。
ruby> ary + ["foo", "bar"]
[1, 2, "3", "foo", "bar"]
ruby> ary * 2
[1, 2, "3", 1, 2, "3"]
We can use index numbers to refer to any part of a array.
我们可以通过数字索引来引用数组的任何部分。
ruby> ary[0]
1
ruby> ary[0,2]
[1, 2]
ruby> ary[0..1]
[1, 2]
ruby> ary[-2]
2
ruby> ary[-2,2]
[2, "3"]
ruby> ary[-2..-1]
[2, "3"]
(Negative indices mean offsets from the end of an array, rather than the beginning.)
(负数的索引代表从数组的末尾开始,而不是从头开始。)
Arrays can be converted to and from strings, using join and split respecitvely:
数组可以被转换为字符串,字符串也可以被转换为数组,分别使用join方法和split方法:
ruby> str = ary.join(":")
"1:2:3"
ruby> str.split(":")
["1", "2", "3"]
Hashes
散列
An associative array has elements that are accessed not by sequential index numbers, but by keys which can have any sort of value. Such an array is sometimes called a hash or dictionary;
关联数组有一些元素,这些元素不是通过顺序索引号访问的,而是通过键来访问,这些键可以是任何类型的值。这样的数组有时被称为散列或字典。
In the ruby world, we prefer the term hash. A hash can be constructed by quoting pairs of items within curly braces ({}). You use a key to find something in a hash, much as you use an index to find something in an array.
在Ruby的世界里,我们更喜欢将它称之为散列。可以通过在花括号中引用成对的散列项来构造散列。你通过键在散列中查找散列项,就如同你用索引在数组中查找数组元素一样。
ruby> h = {1 => 2, "2" => "4"}
{1=>2, "2"=>"4"}
ruby> h[1]
2
ruby> h["2"]
"4"
ruby> h[5]
nil
ruby> h[5] = 10 # appending an entry 添加一个哈希项
10
ruby> h
{5=>10, 1=>2, "2"=>"4"}
ruby> h.delete 1 # deleting an entry by key 通过键删除一个哈希项
2
ruby> h[1]
nil
ruby> h
{5=>10, "2"=>"4"}
上一章 正则表达式
下一章 再读“简单示例”