在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
#E8.1-1.rb
=begin 数组的索引从0开始,一直到数组的长度减去1; 负数表示从数组末尾开始的索引; 用一对数字来索引数组,第一个数字表示开始位置,第二数字表示从开始位置起的元素数目 =end 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].join(",") ,"\n" #4, 5, 6 print arr[-3,2] ,"\n" #[7, 8] #Ruby的数组大小是动态的,你能够随时增加、删除数组元素。 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].join(",") ,"\n" #打印2号索引位置元素 #a,b,c 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" #获取新数组 a=%W(a b c d e f g h i j k)
p a #=>["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
#获取指定索引数组元组,构建一个新的数组
#数组运算
aaaa=["aa",4,5,"bb"] bbbb=[4,1,3,2,5] print (aaaa + bbbb).join(" ") ,"\n" #aa 4 5 bb 4 1 3 2 5 print (aaaa * 2).join(" ") ,"\n" #aa 4 5 bb aa 4 5 bb print (bbbb - aaaa).join(" ") ,"\n" #1 3 2 #并运算;交运算 print (aaaa | bbbb).join(",") ,"\n" #aa,4,5,bb,1,3,2 print (aaaa & bbbb).join(",") ,"\n" #4,5 a11=[1,2,3] #获取数组的并集 #获取数组的交集 #获取差集 #删除重复的元组 #排序;倒置 print bbbb.sort().join(",") ,"\n" #1,2,3,4,5 print aaaa.reverse.join(",") ,"\n" #bb,5,4,aa #collect方法 以数组的形式返回操作结果
a=%w(foo nbar nbuz)
b=a.collect{|i| i.upcase}
p b #=>["FOO", "NBAR", "NBUZ"]
#数组初始化,如果数组元素是对象或者hash对象,应当使用指定的block作为数组初始化元素 a=Array.new(3){[0,0]} |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论