##########################  Containers   #############################
##########################  Arrays   #################################
#The class Array holds a collection of object references.
#You can create arrays by using literals or by explicitly creating an Array object.
#A literal array is simply a list of objects between square brackets.
a = [3.14, "pie", 99]
a.class   #Array
a.length  #3
a[0]      #3.14
a[3]      #nil

b = Array.new
b.class   #Array
b.length  #0
b[0] = "second"
b[1] = "array"

#Arrays are indexed using the [ ] operator. As with most Ruby operators, this is actually
#a method (an instance method of class Array) and hence can be overridden in subclasses.
a = [1, 3, 5, 7, 9]
a[-1]  #9
a[-2]  #7
a[-99] #nil

#You can also index arrays with a pair of numbers, [ start, count ]. This returns a
#new array consisting of references to count objects starting at position start.
a = [1, 3, 5, 7, 9]
a[1, 3]   #[3,5,7]
a[3, 1]   #[7]
a[-3, 2]  #[5,7]


#Finally, you can index arrays using ranges, in which start and end positions are separated
#by two or three periods. The two-period form includes the end position, and the
#three-period form does not.
a = [1, 3, 5, 7, 9]
a[1..3]  #[3,5,7]
a[1...3] #[3,5]

#The [ ] operator has a corresponding [ ]= operator, which lets you set elements in the array.
a = [1, 3, 5, 7, 9]
a[1] = "bat"
a[3] = [9, 8]

a = [1, 3, 5, 7, 9]    
a[2, 2] = 'cat'   #[1,3,'cat',9]
a[2, 0] = 'dog'   #[1,3,'dog','cat',9]
a[1,1] = [9,8,7]  #[1,9,8,7,'dog','cat',9]
a[0..3] = []      #['dog', 'cat', 9]
a[5..6] = 99, 98  #['dog', 'cat', 9, nil, nil, 99, 98]
#Arrays have a large number of other useful methods. Using these, you can treat arrays
#as stacks, sets, queues, dequeues, and fifos.

posted on 2008-04-06 21:26  IT Person  阅读(224)  评论(0)    收藏  举报