ruby学习笔记(6)-Array的使用

ruby的数组基本使用,跟c#中的数组比起来,最不习惯的区别在于允许负索引(跟javascript到有几分相似)

arr=[3,4,5,6,7,8,9]

puts arr[0]  # 3
puts arr.first  # 3
puts arr[arr.length-1] # 9
puts arr[arr.size-1] # 9
puts arr.last  #9
puts arr[-1] #9,下标为-1,即相当于取最后一个元素
puts arr[-2] #8,倒着取第二个数
print arr[1..3]   ,"\n" #456,取下标从1到3的元素
print arr[-3,2]   ,"\n" #倒数第三个元素开始,连续取2个元素,即7,8

复杂一点的应用如下,这里要特意指出的是,ruby中的数组天生就已经实现了堆栈与队列,这一点想得很周到.

#来自"Ruby语言入门教程v1.0"中的E8.1-3.rb

arr=[4,5,6]     
print arr.join(", "),"\n" # 4, 5, 6

arr[4] = "m" #将第5个元素赋值为m
print arr.join(", "),"\n" #第4个元素因为没赋值,所以为空,输出结果为4, 5, 6, , m
print arr[3] ,"\n" #第4个元素为空,所以输出nil

arr.delete_at(3) #删除第4个元素    
print arr.join(", "),"\n" #输出 4, 5, 6, m

arr[2] = ["a","b","c"]  #将第3个元素"6",重新赋值为一维数组[a, b, c]

puts arr[0] # 4
puts arr[1] # 5
puts arr[2] # a,b,c 注意:用puts输出时,会自动把每个元素添加\n
puts arr[3] # m

print arr.join(", "),"\n" # 4, 5, a, b, c, m
print arr[2] ,"\n" # abc

arr[0..1] = [7,"h","b"]  #将前面二个元素4,5换成7,h,b
print arr.join(", "),"\n" # 7, h, b, a, b, c, m

arr.push("b" )  #将b压入数组尾部  
print arr.join(", "),"\n"# 7, h, b, a, b, c, m, b


arr.delete(["a","b","c"] )  #删除数组中匹配["a","b","c"]的元素,即arr[2],注意前面的arr[2] = ["a","b","c"] 
print arr.join(", "),"\n" # 7, h, b, m, b

arr.delete("b")  #将所有b元素删除   
print arr.join(", "),"\n" # 7, h, m

arr.insert(2,"d") # 在第3个元素处插入d,如果后面还有元素,则索引后移
print arr.join(", "),"\n" #7, h, d, m

arr<<"f"<<2  #将元素f,2加入到数组最后,类似前面的push用法
print arr.join(", "),"\n" # 7, h, d, m, f, 2
arr.pop #弹出一个元素,与前面的push结合起来,ruby中的数组本身就是一个堆栈
print arr.join(", "),"\n" #7, h, d, m, f
arr.shift #元素左移一位,即实现了队列
print arr.join(", "),"\n" #h, d, m, f

arr.clear #清空元素
print arr.join(", "),"\n"

最后讲一个要注意的地方:array的each与delete一起用时,有时候会出现意想不到的效果!

#
arr = [1,[2,3],2,3,4,5,6]
print arr.join(","),"\n" #1,2,3,2,3,4,5,6

arr.delete([2,3])
print arr.join(","),"\n" #1,2,3,4,5,6

arr.each{|x| arr.delete(x)};
print arr.join(","),"\n" #2,4,6 注意这里:array对象each,delete一起使用时,使用不当会把自身的"部分"元素给删除掉


posted @ 2010-02-11 21:00  菩提树下的杨过  阅读(1133)  评论(0编辑  收藏  举报