一. 建立一个数组
ruby 代码
- #E8.1-1.rb
- arr1=[]
- arr2=Array.new
- arr3=['4 ','5 ','6 ']
- print arr1, "\n"
- print arr2, "\n"
- print arr3, "\n"
运行结果:
>ruby E8.1-1.rb
4 5 6
>Exit code: 0
二. 访问数组元素
Ruby以整数作为下标,访问数组元素通过数组下标,数组下标称作数组索引比较好一些。
ruby 代码
- #E8.1-2.rb
- 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
- puts arr[-2] # => 8
- print arr[1..3] ,"\n" # => 456
- print arr[-3,2] ,"\n" # => 78
数组的索引从0开始,一直到数组的长度减去1;负数表示从数组末尾开始的索引;用一对数字来索引数组,第一个数字表示开始位置,第二数字表示从开始位置起的元素数目。
三. 增加、删除数组元素
Ruby的数组大小是动态的,你能够随时增加、删除数组元素。
print arr.join(", "),"\n" 意思是:将数组arr转换成字符串输出,用", "隔开每个元素,并且换行。
ruby 代码
- #E8.1-3.rb
- arr=[4,5,6]
- print arr.join(", "),"\n" # => 4, 5, 6
- arr[4] = "m" #把4号索引位置元素赋值为"m"
- print arr.join(", "),"\n" # => 4, 5, 6, , m
- print arr[3] ,"\n" #打印3号索引位置元素 # => nil
- arr.delete_at(3) #删除3号索引位置元素
- print arr.join(", "),"\n" # => 4, 5, 6, m
- arr[2] = ["a","b","c"] #把2号索引位置元素赋值为["a","b","c"]
- print arr.join(", "),"\n" # => 4, 5, a, b, c, m
- print arr[2] ,"\n" #打印2号索引位置元素 # => abc
- arr[0..1] = [7,"h","b"] #把0..1号元素替换为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"]
- print arr.join(", "),"\n" # => 7, h, b, m, b
- arr.delete("b") #删除所有元素"b"
- print arr.join(", "),"\n" # => 7, h, m
- arr.insert(3,"d") #在3号索引位置插入元素"d"
- print arr.join(", "),"\n" # => 7, h, m, d
- arr<<"f"<<2 #加入元素"f";加入元素2
- print arr.join(", "),"\n" # => 7, h, m, d, f, 2
- arr.pop #删除尾元素
- print arr.join(", "),"\n" # => 7, h, m, d, f
- arr.shift #删除首元素
- print arr.join(", "),"\n" # => h, m, d, f
- arr.clear #清空数组arr
- print arr.join(", "),"\n" # =>
四. 数组运算
ruby 代码
- #E8.1-4.rb
- aaaa=[" aa ",4,5," bb "]
- bbbb=[4,1,3,2,5]
- print aaaa + bbbb ,"\n" # => aa 45 bb 41325
- print aaaa * 2 ,"\n" # => aa 45 bb aa 45 bb
- print bbbb - aaaa ,"\n" # => 132
- #并运算;交运算
- print aaaa | bbbb ,"\n" # => aa 45 bb 132
- print aaaa & bbbb ,"\n" # => 45
- #排序;倒置
- print bbbb.sort ,"\n" # => 12345
- print aaaa.reverse ,"\n" # => bb 54 aa
完整阅读,请看我写的 Ruby语言中文教程all in one