Ruby Array


数组

Ruby数组基础

数组索引从0开始,以 -1 结束

获取数组元素

arr = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

at

arr.at(2) #”C”

fetch

当数值不存在时,以默认参数显示

arr.fetch(100, “no”) #=> “no”

sample

随机取值

first

first, second, last ……

arr.first

take

显示前N条记录

arr.take(3) #=> [“a”, “b”, “c”]

slice

arr.slice(1) #=> [ “b”] arr.slice(0, 2) #=> [“a”, “b”] slice(range) → new_ary or nil

slice!

slice(index) → obj or nil slice(start, length) → new_ary or nil slice(range) → new_ary or nil

drop

与take相反, 删除前N条记录

arr.drop(3) #=> [“d”, “e”, “f”]

获取数组信息

length

arr.length #=> 6

size

count

arr.count { x x%2 == 0 }

empty?

是否为空?

include?

arr.include?(“z”)

数组操作

添加元素

push

往数组中添加元素,在最后插入

arr.push(100)

等同

arr « 100

unshift

在数组开始处插入元素

arr.unshift(0) # => [0, “a”, “b”, “c”, “d”, “e”, “f”]

insert

指定位置插入

arr.insert(3, ‘mm’)

或者插入多个元素

arr.insert(3, ‘mm’, ‘nn’)

删除元素

pop

删除数组最后一位

arr.pop

shift

删除数组首位

arr.shift

delete_at

根据索引删除元素

arr.delete_at(2)

delete

删除数组中元素

arr.delete(“a”)

删除元素不存在,返回结果

a.delete(“z”) { “not found” }

compact

删除数组中 空值

arr = ['foo', 0, nil, 'bar', 7, 'baz', nil]
arr.compact  #=> ['foo', 0, 'bar', 7, 'baz']
arr          #=> ['foo', 0, nil, 'bar', 7, 'baz', nil]
arr.compact! #=> ['foo', 0, 'bar', 7, 'baz']
arr          #=> ['foo', 0, 'bar', 7, 'baz']

uniq

去除数组中重复值

uniq! 会对原数组影响, 同上

reverse_each

倒序操作

arr.reverse_each { word p word }

map

map! 赋值操作会对原数组影响, 同compact

arr = [1,3,6]
arr.map! { |a| a**2 }

collect

arr.collect { x x + “!” } #=> [“a!”, “b!”, “c!”, “d!”]

选择元素

对原数组无影响

select

reject

[1, 2, 3, 4, 5].reject { num num.even? } #=> [1, 3, 5]

drop_while

arr = [1, 2, 3, 4, 5, 6]
arr.select { |a| a > 3 }     #=> [4, 5, 6]
arr.reject { |a| a < 3 }     #=> [3, 4, 5, 6]
arr.drop_while { |a| a < 4 } #=> [4, 5, 6]
arr                          #=> [1, 2, 3, 4, 5, 6]

对原数组有影响

delete_if

keep_if

arr.delete_if { |a| a < 4 } #=> [4, 5, 6]
arr                         #=> [4, 5, 6]

arr = [1, 2, 3, 4, 5, 6]
arr.keep_if { |a| a < 4 } #=> [1, 2, 3]
arr                       #=> [1, 2, 3]

&

取数组集中相同值

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]

* int

新数组

[ 1, 2, 3 ] * 3 #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]

* str

生成新字符串

[ 1, 2, 3 ] * “,” #=> “1,2,3”

+

[ 1, 2, 3 ] + [ 4, 5 ] #=> [ 1, 2, 3, 4, 5 ]

concat

[ “a”, “b” ].concat( [“c”, “d”] ) #=> [ “a”, “b”, “c”, “d” ]

<<

[ 1, 2 ] « “c” « “d” « [ 3, 4 ] #=> [ 1, 2, “c”, “d”, [ 3, 4 ] ]

|

[ “a”, “b”, “c” ] [ “c”, “d”, “a” ] #=> [ “a”, “b”, “c”, “d” ]

cycle

死循环

arr.cycle { x puts x }

指定循环次数

arr.cycle(2) { x puts x }

each

对每个数组元素进行操作,返回原数组

arr.each { x puts x, “–” }

each_index

arr.each_index { x print x, “ – “ }

empty?

[].empty? #=> true

eql?

[“a”].eql? “a”

fill

arr.fill(“1”)

fill(obj, start [, length])

arr.fill(“1”, 2, 3) # => [“1”, “1”, “2”, “2”, “2”, “1”]

fill(obj, range )

arr.fill(“9”, 0..3) #=> [“9”, “9”, “9”, “9”, “2”, “1”]

fill(range) { index block }
>arr.fill(-2) { i iii } #=> [“9”, “9”, “9”, “9”, 64, 125]

index

第一个出现该元素的索引

a = [ “a”, “b”, “c” ] a.index(“b”)

rindex

倒序第一个出现该元素的索引

a.rindex(“b”)

rotate

返回一个旋转过的数组

a = [ “a”, “b”, “c”, “d” ] a.rotate #=> [“b”, “c”, “d”, “a”] a.rotate(2) #=> [“c”, “d”, “a”, “b”]

rotate!

flatten!

flatten

把多层数组压成一个数组

a=[[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10] a.flatten

指定数组的层数 flatten(level)

a.flatten(1)

freeze

对数组进行冻结

a = [ “a”, “b”, “c” ] a.freeze #=> [“a”, “b”, “c”]

通过运用freeze,可以创建一个真正意义上的常量。当尝试修改字符,得到的结果是RuntimeError。 “foo”.freeze « “22”

生成一个数组

%w(A B C S D F f).freeze

frozen?

判断是否是冻结过的数组

replace

a = [ “a”, “b”, “c”, “d”, “e” ] a.replace([ “x”, “y”, “z” ]) #=> [“x”, “y”, “z”] a #=> [“x”, “y”, “z”]

to_s

转字符串

inspect

join

[ “a”, “b”, “c” ].join(“-“) #=> “a-b-c”

permutation

组合

a = [1, 2, 3] a.permutation.to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] a.permutation(2).to_a #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]

product

两个数组值进行组合

[1,2,3].product([4,5])     #=> [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]
[1,2].product([1,2])       #=> [[1,1],[1,2],[2,1],[2,2]]
[1,2].product([3,4],[5,6]) #=> [[1,3,5],[1,3,6],[1,4,5],[1,4,6],
                           #     [2,3,5],[2,3,6],[2,4,5],[2,4,6]]
[1,2].product()            #=> [[1],[2]]

rassoc

返回第一个包含该元素的值

a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]
a.rassoc("two")    #=> [2, "two"]
a.rassoc("four")   #=> nil

repeated_combination

生成该长度的数组,元素可以重复

a = [1, 2, 3]
a.repeated_combination(1).to_a  #=> [[1], [2], [3]]
a.repeated_combination(2).to_a  #=> [[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]
a.repeated_combination(3).to_a  #=> [[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3],
                                #    [1,3,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]]
a.repeated_combination(4).to_a  #=> [[1,1,1,1],[1,1,1,2],[1,1,1,3],[1,1,2,2],[1,1,2,3],
                                #    [1,1,3,3],[1,2,2,2],[1,2,2,3],[1,2,3,3],[1,3,3,3],
                                #    [2,2,2,2],[2,2,2,3],[2,2,3,3],[2,3,3,3],[3,3,3,3]]

sort

排序

a = [ "d", "a", "e", "c", "b" ]
a.sort                    #=> ["a", "b", "c", "d", "e"]
a.sort { |x,y| y <=> x }  #=> ["e", "d", "c", "b", "a"]

sort_by

%w{apple pear fig}.sort_by { word word.length}

transpose

a = [[1,2], [3,4], [5,6]] a.transpose #=> [[1, 3, 5], [2, 4, 6]]

zip

对数组进行合并

a = [ 4, 5, 6 ]
b = [ 7, 8, 9 ]
[1, 2, 3].zip(a, b)   #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[1, 2].zip(a, b)      #=> [[1, 4, 7], [2, 5, 8]]