Often we want to operate only on elements of an array that fulfill a specific condition:
Will return elements that match a specific condition
array = [1, 2, 3, 4, 5, 6]
array.select { |number| number > 3 } # => [4, 5, 6]
Will return elements that do not match a specific condition
array = [1, 2, 3, 4, 5, 6]
array.reject { |number| number > 3 } # => [1, 2, 3]
Both #select
and #reject
return an array, so they can be chained:
array = [1, 2, 3, 4, 5, 6]
array.select { |number| number > 3 }.reject { |number| number < 5 }
# => [5, 6]