ruby 数组的使用

01.数组的创建和初始化
a = Array.[](1,2,3,4)
b = Array[1,2,3,4]
c = [1,2,3,4]
d = Array.new #创建一个空数组
e = Array.new(3) #[nil,nil,nil] 初始大小3
f = Array.new(3,"xx") #["xx","xx","xx"] 初始大小3 初始值"xx"
f[0].capitalize! #=> ["Xx","Xx","Xx"]
g = Array.new(3){"yy"} #=> ["yy","yy","yy"]
g[0].capitalize! #=>["Yy","yy","yy"]
--------------------------------------------------------------------
02.数组元素的访问和赋值
a = [1,2,3,4,5,6]
b = a[0] #=>11位
c = a.at[0] #=>11位时
d = a[-2] #=>5 倒数第2位
e = a.at[-2] #=>5 当倒数第2位
f = a[9] #=>nil 不存在第9位
g = a.at[9] #=>nil 当第9位不存在
h = a[3,3] #=>[4,5,6] 从第4位开始,一共3个
i = a[2..4] #=>[3,4,5] 第2位后 到第4位之间
j = a[2...4] #=>[3,4] 第2位后 到第4位之前(不包括4位)

a[1] = 8 #=> [1,8,3,4,5,6] 第2位被重新复制
a[1,3] = [10,30,30] #=>  [1,10,30,30,5,6] 从第2为开始替换数组 共3位
a[0..3] = [2,4,6,8] #=> [2,4,6,8,5,6] 从第1位开始到第4位 替换
a[-1] = 12 #=> [2,4,6,8,5,12] 替换最后一位

k = [2,4,6,8,10]
k[1..2] = [3,3,3] #=>[2,3,3,3,8,10] 替换第2位~第三位之间的
k[7] = 99 #=> [2,3,3,3,8,10,nil,99] 第8位增加997位不存在

m = [1,3,5,7,9]
m[2] = [20,30] #=> [1,2,[20,30],7,9] 把第3位替换为此数组

m = [1,3,5,7,9]
m[2..2]=[20,30] #=> [1,2,20,30,7,9] 在第2位之间加入数组

x = [0,2,4,6,8,10,12]
a = x.slice(2) #=>4 取第3位 
b = x.slice(2,4) #=>[4,6,8,10] 从第3位开始取 4个数
c = x.slice(2..4) #=>[4,6,8] 从第3位..到第5位
x.first #=>0 取第1位
x.last #=>12 取最后1位

x = [10,20,30,40,50,60]
y = x.values_at(0,1,4) #=>[10,20,50] 值在125位时,分别是什么
z = x.values_at(0..2,5) #=>[10,20,50,60] 值在1位~3位之间,6位分别是什么
--------------------------------------------------------------------
03.确定数组的长度
x = ["a","b","c","d"]
a = x.length #=>4
a = x.size #=>4
y = [1,2,nil,nil,3,4]
c = y.size  #=>6
d = y.length #=>6
e = y.nitems #=>4
--------------------------------------------------------------------
04.数组的比较
a = [1,2,3,9,9]
b = [1,2,4,1,1]
c = a <=> b #=> -1 意思是 a

d = [1,2,3]
e = [1,2,3,4]
c = a <=> b #=> -1 意思是 a

定义一个比较方法class Comparable,因为数组默认只有 <=> 现在通过自写class增加 < > <= >=
class Comparable
def <(other)
(self <=>other) == -1
end
def <=(other)
(self < other) or (self == other)
end
def >(other)
(self <=> other) == 1
end
def >=(other)
(self > other) or (self == other)
end
end
然后就可以直接数组 a < b 返回true
--------------------------------------------------------------------
05.数组的排序
words = %w(the quick brown fox) #定义数组
words.sort #=> ["brown","fox","quick","the"] #sort进行排序
正常排序
a.sort #=> ["1", "2", "3", "5", "6", "four", "three", "two"]
另一方法比较排序 返回1
a.sort{|x,y| x.to_s <=> y.to_s} #=> ["1", "2", "3", "5", "6", "four", "three", "two"]
相反比较排序 返回-1
a.sort{|x,y| x.to_s <=> y.to_s} #=> ["two", "three", "four", "6", "5", "3", "2", "1"]
文件大小排列
files.sort{|x,y| File.size(x) <=> File.size(y)}
或
files.sort_by{|x| File.size(x)}
按名字,年龄,身高排列
lists.sort_by{|x| x.name,x.age,x.height}
--------------------------------------------------------------------
06.根据条件从数组中选择,(数组中查询)
x = [5,8,12,9,4,30]
x.detect{|e| e%6 ==0} #=>12 可以被6整除(取余为0的)
x.find{|e| e%2 ==0} #=>8 可以被2整除(取余为0的) 只返回第一个数组
x.find_all{|e| e%2 ==0} #=>[8,12,4,30] 可以被2整除(取余为0的) 返回所有满足条件的
x.select{|e| e%2 ==0} #=>[8,12,4,30] 可以被2整除(取余为0的) 返回所有满足条件的
取相反的
x.reject{|e| e%2 ==0} #=>[5,9] 可以被2整除(取余为0的) 返回所有满足相反条件的

正则查询
a = %w[January February March April May]
#=> ["January", "February", "March", "April", "May"]
a.grep(/ary/)
#=> ["January", "February"]
a.grep(/ary/){|i| i.length}
#=> [7, 8] 查询出来的内容转换为个数.

查询1224之间的数平方
b = [1,20,5,7,13,33,15,28]
#=> [1, 20, 5, 7, 13, 33, 15, 28]
b.grep(12..24){|n| n*n}
#=> [400, 169, 225]

找最大最小
a.max #=> "May"
a.min #=> "April"

翻转一下对比结果
a.min{|x,y| x.reverse <=> y.reverse}
#=> "March" 
a.max{|x,y| x.reverse <=> y.reverse}
#=> "February"

索引最大最小位置
a.index a.min
#=> 3
a.index a.max
#=> 4
--------------------------------------------------------------------
07.使用专门的索引函数
08.实现稀疏矩阵
参照168--------------------------------------------------------------------
09.数组作为数字合集
删除重复项(uniq或uniq!)
a=[1,2,3,4,5]
b=[3,4,5,6,7]
c = a | b
#=> [1, 2, 3, 4, 5, 6, 7] "或"集合
d = a & b  "与"集合
#=> [3, 4, 5]
e = a - b
#=> [1,2] "差"集合
f = a |= b
#=> [1, 2, 3, 4, 5, 6, 7] 累积 等同 "或"集合

class Array
def ^(ohter)
(self | other) - (self & other)
end
end

x=[1,2,3,4,5]
y=[3,4,5,6,7]
z=x^y 
#=>[1,2,6,7] 查不同

查是否存在
x = [1,2,3]
x.include? 2
#=>true
例如:
if x.include? 2
puts "yes"
else
puts "no"
end
例如: in
class Object
def in(other)
other.include? self
end
end
2.in x
#=>true 在x中有 2
例如:subset?
class Array
def subset?(other)
self.each do |x|
if !(other.include? x)
return false
end
true
end
def superset?(other)
other.subset?(self)
end
end
a=[1,2,3,4]
b=[2,3]
c=[2,3,4,5]
flag1=c.subset? a #false c是a的子集么?
flag2=b.subset? a #true b是a的子集么?
flag3=c.superset? b #true 相反b是c子集么?

定义通用集,执行差集
universe = [1,2,3,4,5,6]
a = [2,3]
b = universe - a

其他计算集合的 参照172--------------------------------------------------------------------
10.数组的随机化
class Array
def randomize
self.sort_by{rand}  #Kernel模块中的rand方法
end
def randomize!
self.replace(self.randomize)
end
end
x=[1,2,3,4,5]
y=x.randomize #=> [3,2,4,1,5]
x.randomize!  #=> x现在是[3,5,4,1,2] "叹号"意思直接修改自己

随机选取数组中一个元素 
def pick_random
self[rand(self.length)]
end
x.pick_random #=> 2 随机返回一位,即 x[rand(x.length)] 
--------------------------------------------------------------------
11.使用多位数组
class Array3
def initialize
@store =[[[]]]
end
def [][a,b,c]
if @store[a]==nil ||
@store[a][b]==nil ||
@store[a][b][c]==nil
return nil
else
return @store[a][b][c]
end
end
def []=(a,b,c,x)
@store[a] = [[]] if @store[a]=nil
@store[a][b] = [] if @store[a][b]=nil
@store[a][b][c] = x
end
end
x=Array3.new
x[0,0,0]=5
x[0,0,1]=6
x[1,2,3]=99
puts x[1,2,3]
--------------------------------------------------------------------
12.找出一个数组中而不再另一个数组用的元素(差集)
text = %w[the magic words are squeamish ossifrage]
#=> ["the", "magic", "words", "are", "squeamish", "ossifrage"]
dictionary = %w[an are magic the them these words]
#=> ["an", "are", "magic", "the", "them", "these", "words"]
unknown = text - dictionary
#=> ["squeamish", "ossifrage"]
--------------------------------------------------------------------
13.数组的变换或映射
x = %w[alpha bravo charlie delta echo foxtrot]
#=> ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot"]
a = x.collect{|w| w[0..0]}
#=> ["a", "b", "c", "d", "e", "f"]
a = x.collect{|w| w.length}
#=> [5, 5, 7, 5, 4, 7]
c = x.map{|w| w.length}
#=> [5, 5, 7, 5, 4, 7]
x.collect!{|w| w.upcase}
#=> ["ALPHA", "BRAVO", "CHARLIE", "DELTA", "ECHO", "FOXTROT"]
x.map!{|w| w.reverse}
=> ["AHPLA", "OVARB", "EILRAHC", "ATLED", "OHCE", "TORTXOF"]
--------------------------------------------------------------------
14.删除数组中的nil元素
a = [1,2,nil,3,nil,4,5]
#=> [1, 2, nil, 3, nil, 4, 5]
a.compact
#=> [1, 2, 3, 4, 5]
a.compact!
#=> [1, 2, 3, 4, 5]
a
#=> [1, 2, 3, 4, 5]
--------------------------------------------------------------------
15.删除数组中特定元素
a = [10,12,14,16,18]
#=> [10, 12, 14, 16, 18]
a.delete_at(3)
#=> 16 #删除第4位,返回被删除对象,如果不存在返回nil
a
#=> [10, 12, 14, 18]
a.delete(10) 
#=>10 #返回10

x = %w[alpha bravo charlie delta echo foxtrot]
#=> ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot"]

x.delete("delta"){"不存在已经被删除"}
#=> "delta" #否则返回 "不存在已经被删除"

x.delete_if{|y| y.length==7}
#=> ["alpha", "bravo", "delta"] #删除指定条件的,没有修改返回nil 和reject!相似

a = x.slice(2)
#=> "charlie" #删除第3位

a = x.slice!(2)
=> "charlie"  #删除第3位,并修改x

x.pop
=> "foxtrot" #从数组最右侧开始删除,并修改x

x.shift
=> "alpha" #从数组最右侧开始删除,并修改x

arr = [1,2,3,4,5,6,7,8]
odd = arr.reject{|x| x%2 == 0} 
#=>[1,3,5,7]  #用reject后接代码块

x.clear 
#=>[]  #删除数组所有
--------------------------------------------------------------------
16.数组的拼接和附加(<< + -= concat)
x=[1,5,9]
#=> [1, 5, 9]
x << 13 
#=> [1, 5, 9, 13]
x << 16 << 18
#=> [1, 5, 9, 13, 16, 18]  #主要时<< 这个符号加入附加 

x=[1,2]
y=[3,4]
z=[5,6]

b=y+z
#=> [3, 4, 5, 6]
b +=x
#=> [3, 4, 5, 6, 1, 2]

z.concat y
#=> [5, 6, 3, 4]
--------------------------------------------------------------------
17.用数组用作栈或队列
push 在数组末尾添加
pop 在数组末尾删除
shift 删除数组开头元素
unshift 在开头添加元素
--------------------------------------------------------------------
18.对数组进行迭代
list=%w(i am chong mu)
list.each do |x|
p "#{x}"
end

按顺序迭代
words = %w(Son I am able she said)
#=> ["Son", "I", "am", "able", "she", "said"]
str=""
#=> ""
words.reverse_each{|w| str += "#{w} "}
#=> ["Son", "I", "am", "able", "she", "said"] 
str 
#=> "said she able am I Son" #返回反向字符串 

将素和索引都传递给代码块
x=["alpha","beta","gamma"]
#=> ["alpha", "beta", "gamma"]
x.each_with_index do |x,i|
puts "Element #{i} is #{x}"
end
Element 0 is alpha
Element 1 is beta
Element 2 is gamma
=> ["alpha", "beta", "gamma"]

按随机对数组进行迭代
def random_each
temp = self.random
temp.each{|x| yield x}
end

words.random_each{|x| str += "#{x} "}
str #是一个随机的排列
--------------------------------------------------------------------
19.插入分隔符以形成字符串
words = %w(Son I am able she said)
#=> ["Son", "I", "am", "able", "she", "said"]
words.join(",")
#=> "Son,I,am,able,she,said"

words * " and "
#=> "Son and I and am and able and she and said"

list = %w[A B C D E F]
#=> ["A", "B", "C", "D", "E", "F"]
b=list[0..-2] * ", " + ", and " + list[-1]
#=> "A, B, C, D, E, and F"
--------------------------------------------------------------------
20.颠倒数组
a=[1,2,3]
#=> [1, 2, 3]
a.reverse
#=> [3, 2, 1]
a.reverse!
#=> [3, 2, 1]
a
#=> [3, 2, 1]
--------------------------------------------------------------------
21.删除数组中重复的元素
a=[2,3,3,2,6,5,9,8,7]
#=> [2, 3, 3, 2, 6, 5, 9, 8, 7]
a.uniq
#=> [2, 3, 6, 5, 9, 8, 7]
a
#=> [2, 3, 3, 2, 6, 5, 9, 8, 7]
a.uniq!
#=> [2, 3, 6, 5, 9, 8, 7]
a
#=> [2, 3, 6, 5, 9, 8, 7]
--------------------------------------------------------------------
22.数组的交织
a=[1,2,3,4]
#=> [1, 2, 3, 4]
b=["a","b","c","d"]
#=> ["a", "b", "c", "d"]
c=a.zip(b)
#=> [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
c
#=> [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
d=c.flatten  
#=> [1, "a", 2, "b", 3, "c", 4, "d"]
--------------------------------------------------------------------
23.计算数组中值的频率
class Array
def count
k=Hash.new(0)
self.each{|x| k[x]+=1}
k
end
end
meal=%w[spam spam eggs ham eggs spam]
items=meal.count
#items is {"ham"=>1,"spam"=>3,"eggs"=>2}
spams=items["spam"] #3
--------------------------------------------------------------------
24.将数组颠倒为散列
class Array
def invert
h={}
self.each_with_index{|x,i| h[x]=i}
h
end
end
a=["red","yellow","orange"]
#=> ["red", "yellow", "orange"]
a.invert
#=> {"orange"=>2, "red"=>0, "yellow"=>1}
--------------------------------------------------------------------
25.同步多个数组的排序
class Array
def sort_index
d=[]
self.each_with_index{|x,i| d[i]=[x,i]}
if block_given?
d.sort{|x,y| yield x[0],y[0].collect{|x| x[1]}}
else
d.sort.collect{|x| x[1]}
end
end
def sort_with(ord=[])
return nil if self.length!=ord.length
self.values_at(*ord)
end
end

a=[21,33,11,34,36,24,14]
b=a.sort_index
a2=a.sort_with(b)
c=a.sort_index{|x,y| x%2 <=> y%2}
a3=a.sort_with(c)

p a #[21,33,11,34,36,24,14]
p b #[2,6,0,5,1,3,4]
p a2 #[11,14,21,24,33,34,36]
p c #[6,5,4,3,2,1,0]
p a3 #[14,24,36,34,11,33,21]
--------------------------------------------------------------------
26.给新数组元素指定默认值
a = Array.new
#=> []
a[0]="x"
#=> "x"
a[3]="y"
#=> "y"
a
#=> ["x", nil, nil, "y"]
class ZArray < Array
def [](x)
if x >size
for i in size+1..x
self[i]=0
end
end
v = super(x)
end

def []=(x,v)
max=size
super(x,v)
if size - max > 1
(max..size-2).each do |i|
self[i]=0
end
end
end
end

num=ZArray.new
num[1]=1
num[2]=4
num[5]=25
#=>num is now [0,1,4,0,0,25]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值