Ruby数组方法非常丰富,可以帮助您轻松应对各种复杂需求。以下是一些常用数组方法及其用途:
Array#select
:筛选数组中满足条件的元素。numbers = [1, 2, 3, 4, 5, 6]
even_numbers = numbers.select { |number| number.even? }
puts even_numbers.inspect # 输出: [2, 4, 6]
Array#reject
:筛选数组中不满足条件的元素。numbers = [1, 2, 3, 4, 5, 6]
odd_numbers = numbers.reject { |number| number.even? }
puts odd_numbers.inspect # 输出: [1, 3, 5]
Array#map
:对数组中的每个元素执行指定操作,并返回一个新数组。numbers = [1, 2, 3, 4, 5]
squares = numbers.map { |number| number * number }
puts squares.inspect # 输出: [1, 4, 9, 16, 25]
Array#reduce
:对数组中的所有元素执行指定操作,最终返回一个值。numbers = [1, 2, 3, 4, 5]
sum = numbers.reduce(0) { |total, number| total + number }
puts sum.inspect # 输出: 15
Array#group_by
:根据指定条件将数组中的元素分组。numbers = [1, 2, 3, 4, 5, 6]
grouped_numbers = numbers.group_by { |number| number.even? }
puts grouped_numbers.inspect # 输出: {true=>[2, 4, 6], false=>[1, 3, 5]}
Array#sort
:对数组中的元素进行排序。numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = numbers.sort
puts sorted_numbers.inspect # 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Array#reverse
:反转数组中的元素顺序。numbers = [1, 2, 3, 4, 5]
reversed_numbers = numbers.reverse
puts reversed_numbers.inspect # 输出: [5, 4, 3, 2, 1]
Array#compact
:移除数组中的空值(如nil
和空字符串)。numbers = [1, 2, nil, 4, "", 6]
compact_numbers = numbers.compact
puts compact_numbers.inspect # 输出: [1, 2, 4, 6]
Array#drop
:移除数组中的前n个元素。numbers = [1, 2, 3, 4, 5]
dropped_numbers = numbers.drop(2)
puts dropped_numbers.inspect # 输出: [3, 4, 5]
Array#take
:从数组的开头取出n个元素。numbers = [1, 2, 3, 4, 5]
taken_numbers = numbers.take(3)
puts taken_numbers.inspect # 输出: [1, 2, 3]
这些方法可以根据您的复杂需求进行组合和嵌套使用,以实现更高级的功能。