Ruby数组操作的总结
1、数组定义
arr1 = []
arr2 = Array.new
arr3 = ['1','2','3']
2、输出
print arr3,"\n" #123
puts arr3[0] #1
print arr3.join(",") #1,2,3
3、访问数组元素
arr1[0]
arr1[-1] #这个比较有意思,意思是最后一个的数据
arr1.first
arr1.last
arr1.max
arr1.min
arr1.length
arr1.size
4、数组操作
arr3[4] = '5' #此时arr3[3]默认尾nil
arr3.delete_at(3) #删除指定下标的元素
arr3[2] = ["3a","3b","3c"] #可以这样来做
arr3.delete(["3a","3b","3c"]) #可以删除上面添加的
arr3.push('6') #插入元素
arr3.insert(3,"b") #在指定位置插入新元素
arr3<<"f"<<2 #从左至右一次加入元素
arr3.pop #删除尾元素
arr3.shift #删除首元素
arr3.clear #清空数组
5、数组运算
aaa = [" aa ",4,5," bb "]
bbb = [4,1,3,2,5]
print aaa + bbb,"\n" # aa 45 bb 41325
print aaa*2,"\n" # aa 45 66 aa 45 66
print bbb - aaa #132
print aaa | bbb,"\n" # aa 45 bb 132
print aaa & bbb,"\n" #45
print bbb.sort,"\n" #12345 排序
print aaa.reverse,"\n" # bb 54 aa 倒置
print bbb.sort.reverse,"\n" #54321 降序