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]
這些方法可以根據您的復雜需求進行組合和嵌套使用,以實現更高級的功能。