Programming Ruby Array

#array

words=%w|({<| #same as:['(','{','<']
puts words

white=%W(s\s s\t s\r s\n) #same as:["s\s","s\t","s\r","s\n"]
puts white

empty=Array.new #:returns a new empty array
nils=Array.new(3) #[nil,nil,nil]:new array with 3 nil elements
zeros=Array.new(4,0) #[0,0,0,0]:new array with 4 0 elements
copy=Array.new(nils) #Make a new copy of an existing array
count=Array.new(3){|i| i+1} #[1,2,3]:3 elements computed from index
p empty
p nils
p zeros
p copy
p count

#assignment:
a=[1,4,9,16]
p a
a[0]="zero" #a is ["zero",1,4,9,16]
p a
a[-1]=1..16 #a is ["zero",1,4,9,16,1..16]
p a
a[8]=64 #a is ["zero",1,4,9,16,nil,nil,nil,64]
p a
a[-10]=100 #Error:can't assign before the start of an array

#the expression returns the specified subarray:
a=('a'..'e').to_a #["a", "b", "c", "d", "e"]
p a
p a[0,0] #:this subarray has zero elements
p a[1,1] #['b']: a one-element array
p a[2,2] #['d','e']:the last two elements of the array
p a[0..2] #['a','b','c']:the first three elements
p a[-2..-1] #['d','e']:the last two elements of the array
p a[0...-1] #['a','b','c','d']] all but the last element


#Use + to concatenate two arrays:
a=[1,2,3]+[4,5] #[1,2,3,4,5]
p a
a=a+6,7,8 #[1,2,3,4,5,[6,7,8]]
p a
a=a+9 #Error:righthand side must be an array


#use concat to append the elements of an array
a=[]
a<<1 #a is [1]
p a
a<<2<<3 #a is [1,2,3]
a<<[4,5,6] #a is [1,2,3,[4,5,6]]
a.concat [7,8] #a is [1,2,3,[4,5,6],7,8]
p a

# The - opperator substracts one array from another
a=['a','b','c','d','a']-['b','c','d'] #['a','a']
p a

#the array class borrows the Boolean operators | and &
a=[1,1,2,2,3,3,4]
b=[5,5,4,4,3,3,2]
p a|b #[1,2,3,4,5]: duplicates are removed
p b|a #[5,4,3,2,1]: elements are the same , but order is different
p a&b #[2,3,4]
p b&a #[4,3,2]


a=('A'..'Z').to_a
a.each{|x| print x} #ABCDEFGHIJKLMNOPQRSTUVWXYZ

#other array methods you may want to look up include
#clear,compact!,delete_if,index,join,pop,push,reverse,reverse_each,rindex,shift,sort,sort!,uniq!,unshift