Filtering arrays

suggest change

Often we want to operate only on elements of an array that fulfill a specific condition:

Select

Returns the elements for which the block is true:

array = [1, 2, 3, 4, 5, 6]
array.select { |number| number > 3 } # => [4, 5, 6]

Reject

Returns the elements for which the block is false:

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]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents