Ruby教程之注释、变量声明以及数组操作

  ## 1、数组定义

  arr1 = []

  arr2 = Array.new

  arr3 = ['1','2','3']

  ## 2、输出

  puts "Output:

  "

  print arr3,"

  " # 输出:["1", "2", "3"]

  puts arr3[0] # 输出:1

  print arr3.join(",") # 输出:1,2,3

  ## 3、访问数组元素

  puts "

  Array Element

  "

  puts "

  ", arr3[0]

  puts "

  ", arr3[-1] #这个比较有意思,意思是最后一个的数据

  puts "

  ", arr3.first

  puts "

  ", arr3.last

  puts "

  ", arr3.max

  puts "

  ", arr3.min

  puts "

  ", arr3.length

  puts "

  ", arr3.size

  ## 4、数组操作

  puts "

  Array method

  "

  puts "

  ", arr3[4] = '5' #此时arr3[3]默认尾nil

  puts "

  ", arr3.delete_at(3) #删除指定下标的元素

  puts "

  ", arr3[2] = ["3a","3b","3c"] #可以这样来做

  puts "

  ", arr3.delete(["3a","3b","3c"]) #可以删除上面添加的

  puts "

  ", arr3.push('6') #插入元素

  puts "

  ", arr3.insert(3,"b") #在指定位置插入新元素

  puts "

  ", arr3<<"f"<<2 #从左至右一次加入元素

  puts "

  ", arr3.pop #删除尾元素

  puts "

  ", arr3.shift #删除首元素

  puts "

  ", arr3.clear #清空数组

  ## 5、数组运算

  puts "

  Array Operator

  "

  aaa = [" aa ",4,5," bb "]

  bbb = [4,1,3,2,5]

  print aaa + bbb,"

  " # 输出:[" aa ", 4, 5, " bb ", 4, 1, 3, 2, 5]

  print aaa*2,"

  " # 输出:[" aa ", 4, 5, " bb ", " aa ", 4, 5, " bb "]

  print bbb - aaa,"

  " # 输出:[1, 3, 2]

  print aaa | bbb,"

  " # 输出:[" aa ", 4, 5, " bb ", 1, 3, 2]

  print aaa & bbb,"

  " # 输出:[4, 5]

  print bbb.sort,"

  " # 输出:[1, 2, 3, 4, 5] 排序

  print aaa.reverse,"

  " # 输出:[" bb ", 5, 4, " aa "] 倒置

  print bbb.sort.reverse,"

  " # 输出:[5, 4, 3, 2, 1] 降序