使用字面量直接定义数组
irb(main):001:0> [1, 2, 3, 4, 5, 6, 7, 8]
=> [1, 2, 3, 4, 5, 6, 7, 8]
使用 <<
操作符直接追加元素
irb(main):004:0> [1, 2, 3, 4, 5, 6, 7, 8] << 9
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
flatten
flatten!
方法可以将多维数组合并成一维数组
irb(main):006:0> [[1, 2], [[3, 4], [5, 6]], [7, 8]].flatten
=> [1, 2, 3, 4, 5, 6, 7, 8]
each_slice
方法可以将一维数组切分成多维数组
irb(main):023:0> [1, 2, 3, 4, 5, 6, 7, 8].each_slice(2).to_a
=> [[1, 2], [3, 4], [5, 6], [7, 8]]
uniq
uniq!
方法直接去除重复的元素
irb(main):007:0> [1, 1, 3, 4, 4, nil, nil].uniq
=> [1, 3, 4, nil]
max
min
方法返回最大最小的元素值
irb(main):008:0> [1, 2, 3, 4].max
=> 4
irb(main):009:0> [1, 2, 3, 4].min
=> 1
first
last
方法返回数组中第一个和最后一个元素
irb(main):010:0> [1, 2, 3, 4].first
=> 1
irb(main):011:0> [1, 2, 3, 4].last
=> 4
delete
delete_at
delete_if
方法可以删除元素、删除指定下表的元素、删除符合条件的元素
irb(main):041:0> ary = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb(main):042:0> ary.delete(2)
=> 2
irb(main):043:0> ary
=> [1, 3, 4, 5]
irb(main):044:0> ary = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb(main):045:0> ary.delete_at(2)
=> 3
irb(main):046:0> ary
=> [1, 2, 4, 5]
irb(main):047:0> ary = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb(main):048:0> ary.delete_if { |i| i.even? }
=> [1, 3, 5]
数组的加减操作?
irb(main):053:0> [1, 2, 3] + [3, 4, 5]
=> [1, 2, 3, 3, 4, 5]
irb(main):054:0> [1, 2, 3] - [3, 4, 5]
=> [1, 2]
join
方法可以连接数组中的元素
irb(main):014:0> [1, 2, 3].join(", ")
=> "1, 2, 3"
irb(main):019:0> "1, 2, 3".split(", ").map { |i| i.to_i }
=> [1, 2, 3]
include?
方法可以查找数组中是否包含指定元素
irb(main):020:0> [1, 2, 3, 4].include? 5
=> false
irb(main):021:0> [1, 2, 3, 4].include? 4
=> true
find
方法返回符合条件的元素,找不到的情况返回 nil
irb(main):027:0> [1, 2, 3, 4].find { |i| i > 2 }
=> 3
irb(main):028:0> [1, 2, 3, 4].find { |i| i > 4 }
=> nil
select
方法返回符合条件的所有元素,找不到的情况返回空数组 []
irb(main):030:0> [1, 2, 3, 4].select { |i| i > 2 }
=> [3, 4]
irb(main):031:0> [1, 2, 3, 4].select { |i| i > 4 }
=> []
concat
方法来连接数组
irb(main):033:0> [1, 2, 3].concat([4, 5, 6])
=> [1, 2, 3, 4, 5, 6]
|
&
操作符来获取数组的并集和交集
irb(main):034:0> [1, 2, 3] | [3, 4, 5]
=> [1, 2, 3, 4, 5]
irb(main):035:0> [1, 2, 3] & [3, 4, 5]
=> [3]
each
each_with_index
迭代数组
irb(main):035:0> [1, 2, 3].each { |item| }
irb(main):045:0> [1, 2, 3].each_with_index { |item, index| }
数组转哈希
irb(main):017:0> [['foo', 1], ['bar', 4]].to_h
=> {"foo"=>1, "bar"=>4}