Ruby数组 #
一、数组概述 #
数组是Ruby中最常用的集合类型,可以存储任意类型的元素,包括数字、字符串、对象甚至其他数组。
ruby
arr = [1, "hello", :symbol, 3.14, [1, 2, 3]]
arr.class
arr.length
二、创建数组 #
2.1 字面量语法 #
ruby
arr = [1, 2, 3, 4, 5]
arr = []
arr = [1, "hello", :symbol]
arr = %w[apple banana cherry]
arr = %i[one two three]
arr = %W[hello #{world}]
arr = %I[#{key}_one #{key}_two]
2.2 Array方法 #
ruby
Array.new
Array.new(3)
Array.new(3, "x")
Array.new(3) { |i| i * 2 }
Array.new(3) { [] }
Array([])
Array(1..5)
Array("hello")
2.3 其他创建方式 #
ruby
"hello".chars
1..5.to_a
(1..5).to_a
"a".."z".to_a
"a".upto("e").to_a
3.times.to_a
三、数组访问 #
3.1 索引访问 #
ruby
arr = ["a", "b", "c", "d", "e"]
arr[0]
arr[1]
arr[-1]
arr[-2]
arr[10]
arr.at(0)
3.2 切片访问 #
ruby
arr = ["a", "b", "c", "d", "e"]
arr[0, 2]
arr[1, 3]
arr[0..2]
arr[0...2]
arr[1..-1]
arr[-3..-1]
arr.slice(0, 2)
arr.slice(0..2)
3.3 fetch方法 #
ruby
arr = ["a", "b", "c"]
arr.fetch(0)
arr.fetch(10)
arr.fetch(10, "default")
arr.fetch(10) { |i| "索引#{i}不存在" }
3.4 first和last #
ruby
arr = [1, 2, 3, 4, 5]
arr.first
arr.first(2)
arr.last
arr.last(2)
四、数组修改 #
4.1 添加元素 #
ruby
arr = [1, 2, 3]
arr.push(4)
arr << 5
arr.unshift(0)
arr.insert(2, "a", "b")
arr.append(6)
arr.prepend(-1)
4.2 删除元素 #
ruby
arr = [1, 2, 3, 4, 5]
arr.pop
arr.shift
arr.delete(3)
arr.delete_at(1)
arr.delete_if { |n| n > 3 }
arr.reject! { |n| n > 3 }
arr.compact!
arr.uniq!
arr.clear
4.3 替换元素 #
ruby
arr = [1, 2, 3, 4, 5]
arr[0] = "a"
arr[1, 2] = ["b", "c"]
arr.replace([10, 20, 30])
arr.fill(0)
arr.fill("x", 1, 2)
arr.fill { |i| i * 10 }
4.4 修改原数组的方法 #
ruby
arr = [3, 1, 2]
arr.sort!
arr.reverse!
arr.rotate!
arr.shuffle!
arr.map! { |n| n * 2 }
arr.select! { |n| n > 1 }
arr.flatten!
arr.compact!
arr.uniq!
五、数组查询 #
5.1 包含检查 #
ruby
arr = [1, 2, 3, 4, 5]
arr.include?(3)
arr.include?(10)
arr.member?(3)
arr.any? { |n| n > 3 }
arr.all? { |n| n > 0 }
arr.none? { |n| n < 0 }
arr.one? { |n| n == 3 }
5.2 查找元素 #
ruby
arr = [1, 2, 3, 4, 5]
arr.find { |n| n > 3 }
arr.detect { |n| n > 3 }
arr.find_index { |n| n > 3 }
arr.index(3)
arr.rindex(3)
arr.index { |n| n > 3 }
arr.bsearch { |n| n >= 3 }
arr.bsearch_index { |n| n >= 3 }
5.3 统计信息 #
ruby
arr = [1, 2, 2, 3, 3, 3]
arr.size
arr.length
arr.count
arr.count(2)
arr.count { |n| n > 2 }
arr.empty?
arr.nil?
arr.min
arr.max
arr.minmax
arr.sum
arr.average
六、数组迭代 #
6.1 each迭代 #
ruby
arr = [1, 2, 3, 4, 5]
arr.each { |n| puts n }
arr.each_with_index { |n, i| puts "#{i}: #{n}" }
arr.each_index { |i| puts i }
arr.reverse_each { |n| puts n }
6.2 map转换 #
ruby
arr = [1, 2, 3, 4, 5]
arr.map { |n| n * 2 }
arr.map(&:to_s)
arr.collect { |n| n ** 2 }
arr.filter_map { |n| n * 2 if n.even? }
6.3 select过滤 #
ruby
arr = [1, 2, 3, 4, 5]
arr.select { |n| n.even? }
arr.reject { |n| n.even? }
arr.find_all { |n| n > 2 }
arr.filter { |n| n > 2 }
6.4 reduce聚合 #
ruby
arr = [1, 2, 3, 4, 5]
arr.reduce { |sum, n| sum + n }
arr.reduce(0) { |sum, n| sum + n }
arr.reduce(:+)
arr.reduce(1, :*)
arr.inject { |sum, n| sum + n }
arr.sum
6.5 分组 #
ruby
arr = [1, 2, 3, 4, 5, 6]
arr.partition { |n| n.even? }
arr.group_by { |n| n.even? }
arr.slice_when { |a, b| a + 1 != b }.to_a
arr.chunk { |n| n.even? }.to_a
arr.chunk_while { |a, b| a <= b }.to_a
七、数组排序与排列 #
7.1 排序 #
ruby
arr = [3, 1, 4, 1, 5, 9, 2, 6]
arr.sort
arr.sort.reverse
arr.sort { |a, b| b <=> a }
arr.sort_by { |n| -n }
arr.sort_by { |n| n.to_s }
arr.sort_by(&:abs)
7.2 排列组合 #
ruby
arr = [1, 2, 3]
arr.permutation.to_a
arr.permutation(2).to_a
arr.combination.to_a
arr.combination(2).to_a
arr.repeated_permutation(2).to_a
arr.repeated_combination(2).to_a
7.3 旋转与翻转 #
ruby
arr = [1, 2, 3, 4, 5]
arr.rotate
arr.rotate(2)
arr.rotate(-2)
arr.reverse
arr.shuffle
八、数组转换 #
8.1 转字符串 #
ruby
arr = ["a", "b", "c"]
arr.join
arr.join(", ")
arr.to_s
arr.inspect
arr * ", "
8.2 转哈希 #
ruby
arr = [[:a, 1], [:b, 2], [:c, 3]]
arr.to_h
Hash[arr]
Hash[*arr.flatten]
8.3 扁平化 #
ruby
arr = [1, [2, 3], [4, [5, 6]]]
arr.flatten
arr.flatten(1)
arr.flatten!
8.4 转置 #
ruby
arr = [[1, 2], [3, 4], [5, 6]]
arr.transpose
九、数组运算 #
9.1 集合运算 #
ruby
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
a | b
a - b
a & b
a + b
9.2 差集与交集 #
ruby
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
a.difference(b)
a.intersection(b)
a.union(b)
9.3 去重 #
ruby
arr = [1, 2, 2, 3, 3, 3]
arr.uniq
arr.uniq!
arr.uniq { |n| n % 2 }
十、多维数组 #
10.1 创建多维数组 #
ruby
matrix = Array.new(3) { Array.new(3, 0) }
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix = Array.new(3) { |i| Array.new(3) { |j| i * 3 + j + 1 } }
10.2 访问多维数组 #
ruby
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix[0][0]
matrix[1][2]
matrix.dig(1, 2)
matrix[0..1].map { |row| row[0] }
10.3 遍历多维数组 #
ruby
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix.each do |row|
row.each do |cell|
puts cell
end
end
matrix.each_with_index do |row, i|
row.each_with_index do |cell, j|
puts "[#{i}][#{j}] = #{cell}"
end
end
matrix.flatten.each { |n| puts n }
十一、实用示例 #
11.1 数组分块 #
ruby
def chunk_array(arr, size)
arr.each_slice(size).to_a
end
chunk_array([1, 2, 3, 4, 5, 6, 7], 3)
11.2 数组去重保持顺序 #
ruby
def unique_preserve_order(arr)
arr.each_with_object([]) do |item, result|
result << item unless result.include?(item)
end
end
unique_preserve_order([1, 2, 2, 3, 1, 4])
11.3 数组扁平化指定深度 #
ruby
def flatten_depth(arr, depth = 1)
return arr if depth == 0
arr.reduce([]) do |result, item|
if item.is_a?(Array) && depth > 0
result + flatten_depth(item, depth - 1)
else
result + [item]
end
end
end
flatten_depth([1, [2, [3, [4]]]], 2)
11.4 数组随机抽样 #
ruby
def weighted_sample(arr, weights)
total = weights.sum
random = rand * total
arr.each_with_index do |item, i|
return item if random <= weights[i]
random -= weights[i]
end
end
weighted_sample(["a", "b", "c"], [1, 2, 3])
11.5 数组分组统计 #
ruby
def group_count(arr)
arr.each_with_object(Hash.new(0)) { |item, hash| hash[item] += 1 }
end
group_count([1, 2, 2, 3, 3, 3])
十二、总结 #
本章我们学习了:
- 创建数组:字面量、Array.new、%w/%i
- 数组访问:索引、切片、fetch
- 数组修改:添加、删除、替换
- 数组查询:include?、find、count
- 数组迭代:each、map、select、reduce
- 数组排序:sort、sort_by
- 数组运算:并集、交集、差集
- 多维数组:创建、访问、遍历
接下来让我们学习Ruby的哈希!
最后更新:2026-03-27