city=["北京","上海","天津","重庆"] puts city city=Array.new city[0]="北京" city[1]="上海" city[2]="天津" city[3]="重庆" puts city
city=["北京","上海","天津","重庆"] city[4]="香港" puts "数组的长度为:"+city.size.to_s puts city puts "第二个元素为:"+city[1] puts "最后一个元素为:"+city[-1]
city=Array.new city[2]="香港" puts "数组的长度为:"+city.size.to_s puts city
str="深圳" city_1=%W{北京 上海 天津 重庆 杭州 南京 #{str}}#使用%W{...}进行转换 puts city_1.size puts city_1 city_2=%w{北京 上海 天津 重庆 杭州 南京 #{str}}#使用%w{...}进行转换 puts city_2
college=["北京大学","清华大学"] college.unshift("浙江大学","复旦大学") #向数组头部添加元素列表 college.push("南京大学","武汉大学") #向数组尾部添加元素列表 college<<"南开大学" #向数组尾部添加一个元素 puts college.size.to_s puts college puts college.pop #删除并获取数组最后一个元素 puts college.shift #删除并获取数组第一个元素 puts college.size.to_s puts college puts college[2,3] #截取从索引2开始,长度为3的元素列表 puts college[2..3] #截取从索引2开始,到索引3的元素列表 puts college[2...3] #截取从索引2开始,到索引3(不包括)的元素列表
city_1=["北京","上海","天津"] city_2=["重庆","香港"] city_3=city_1+city_2 puts city_3.size.to_s city_1.concat(city_2) puts city_1.size.to_s
a=Array.new p a
a=Array.new(5) p a
a=Array.new(5,0) p a #lang=%W(a b c) lang=%W{a b c} p lang
h={"a"=>"b","c"=>"d"} p h.to_a
s="ab cd efg" a=s.split(" ") p a #p a.include?("ab") #a.each_with_index do |b,i| # p b # p i #end #h = {:aaa => "bbb", :ccc => "ddd"} #h.each_key do |key| # p h[key] #end #h.replace({:a => "b", :c => "d"}) #p h #t = Time.now #p t.strftime("%y")
a=[1,2,3,5,7,9] b=[2,4,6,8,10] #两数组相连 p (a+b) #a数组中的元素减去b数组中与之相同的元素 p (a-b) #(并集)除去两个数组中相同的元素 p (a|b) #(交集)只有两个数组中都相同的元素 p (p&b)
a=[1,2,3,2] a.delete(2) #删除所有与X相同的元素 p a
a=[1,2,3,2] a.delete_at(3) #删除第n个元素 p a
a=[1,2,3,4,5,6,7,8,9,10] a.slice!(1,5) #删除数组中第几到第几个之间的所有数据 p a
a=[1,2,3,4,5,6,7] a[1..6]=[4,5,6,7,8,9] #a[n..m]方法可以选择改变数组 p a
a=[1,2,3,4,5,6,7,8,9] a.each(){|s| p s} a.each_with_index do |c,i| puts "#{i} : #{c}" puts (c+i).to_s end
a=[[1,2],[2,3],[3,4],6] p a.flatten
s = [ 1, 2, 3 ] #=> [1, 2, 3] t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]] a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10] puts a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [ 1, 2, [3, [4, 5] ] ] puts a.flatten(1) #=> [1, 2, 3, [4, 5]] puts a.flatten #=> [1, 2, 3, 4, 5]
a=[1,1,2,2,3,3] p a.uniq #去掉重复的元素
arr=[9,8,7,1,2,5,3] p arr.sort #=> [1, 2, 3, 5, 7, 8, 9] p arr #=> [9, 8, 7, 1, 2, 5, 3] p arr.sort! #=> [1, 2, 3, 5, 7, 8, 9] p arr #=> [1, 2, 3, 5, 7, 8, 9] p arr.sort{|a,b| b<=>a}
[] [nil, nil, nil, nil, nil] [0, 0, 0, 0, 0] ["a", "b", "c"] [["c", "d"], ["a", "b"]] ["ab", "cd", "efg"] [1, 2, 3, 5, 7, 9, 2, 4, 6, 8, 10] [1, 3, 5, 7, 9] [1, 2, 3, 5, 7, 9, 4, 6, 8, 10] false [1, 3] [1, 2, 3] [1, 7, 8, 9, 10] [1, 4, 5, 6, 7, 8, 9] 1 2 3 4 5 6 7 8 9 0 : 1 1 1 : 2 3 2 : 3 5 3 : 4 7 4 : 5 9 5 : 6 11 6 : 7 13 7 : 8 15 8 : 9 17 [1, 2, 2, 3, 3, 4, 6] 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 1 2 3 4 5 [1, 2, 3] [1, 2, 3, 5, 7, 8, 9] [9, 8, 7, 1, 2, 5, 3] [1, 2, 3, 5, 7, 8, 9] [1, 2, 3, 5, 7, 8, 9] [9, 8, 7, 5, 3, 2, 1]
|
请发表评论