数组

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.

您可以通过在方括号中列出一些以逗号分隔的项来创建数组

  1. ruby> ary = [1, 2, "3"]
  2. [1, 2, "3"]

Arrays can be concatenated or repeated just as strings can.

数组可以同字符串一样被连接或重复。

  1. ruby> ary + ["foo", "bar"]
  2. [1, 2, "3", "foo", "bar"]
  3. ruby> ary * 2
  4. [1, 2, "3", 1, 2, "3"]

We can use index numbers to refer to any part of a array.

我们可以通过数字索引来引用数组的任何部分。

  1. ruby> ary[0]
  2. 1
  3. ruby> ary[0,2]
  4. [1, 2]
  5. ruby> ary[0..1]
  6. [1, 2]
  7. ruby> ary[-2]
  8. 2
  9. ruby> ary[-2,2]
  10. [2, "3"]
  11. ruby> ary[-2..-1]
  12. [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方法:

  1. ruby> str = ary.join(":")
  2. "1:2:3"
  3. ruby> str.split(":")
  4. ["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的世界里,我们更喜欢将它称之为散列。可以通过在花括号中引用成对的散列项来构造散列。你通过散列中查找散列项,就如同你用索引数组中查找数组元素一样。

  1. ruby> h = {1 => 2, "2" => "4"}
  2. {1=>2, "2"=>"4"}
  3. ruby> h[1]
  4. 2
  5. ruby> h["2"]
  6. "4"
  7. ruby> h[5]
  8. nil
  9. ruby> h[5] = 10 # appending an entry 添加一个哈希项
  10. 10
  11. ruby> h
  12. {5=>10, 1=>2, "2"=>"4"}
  13. ruby> h.delete 1 # deleting an entry by key 通过键删除一个哈希项
  14. 2
  15. ruby> h[1]
  16. nil
  17. ruby> h
  18. {5=>10, "2"=>"4"}

上一章 正则表达式
下一章 再读“简单示例”