Filtering arrays
suggest changeOften 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]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents