How to Filter Array in Ruby: Simple Guide with Examples
In Ruby, you can filter an array using the
select method, which returns a new array with elements that meet a condition inside a block. Use array.select { |item| condition } to keep only the elements where the condition is true.Syntax
The select method is called on an array and takes a block with a condition. It returns a new array containing only the elements for which the block returns true.
array: The original array you want to filter.select: The method that filters elements.{ |item| condition }: The block whereitemis each element, andconditionis what you check.
ruby
filtered_array = array.select { |item| condition }Example
This example filters an array of numbers to keep only even numbers.
ruby
numbers = [1, 2, 3, 4, 5, 6] even_numbers = numbers.select { |num| num.even? } puts even_numbers.inspect
Output
[2, 4, 6]
Common Pitfalls
One common mistake is using select without a block or with a block that always returns true or false. Another is modifying the original array expecting it to change, but select returns a new array instead.
Also, confusing select with reject can cause wrong results; reject keeps elements where the condition is false.
ruby
numbers = [1, 2, 3, 4] # Wrong: no block given # filtered = numbers.select # Wrong: block always false, returns empty array filtered = numbers.select { |n| false } puts filtered.inspect # Output: [] # Right: filter even numbers filtered = numbers.select { |n| n.even? } puts filtered.inspect # Output: [2, 4]
Output
[]
[2, 4]
Quick Reference
Use select to keep elements matching a condition.
Use reject to remove elements matching a condition.
Remember, both return new arrays and do not change the original.
| Method | Purpose | Returns |
|---|---|---|
| select | Keeps elements where block is true | New filtered array |
| reject | Keeps elements where block is false | New filtered array |
| select! | Filters array in place (modifies original) | Modified original array or nil if no changes |
Key Takeaways
Use
select with a block to filter arrays by a condition.select returns a new array and does not change the original.Make sure the block returns true only for elements you want to keep.
Use
reject to filter out elements matching a condition.Use
select! if you want to modify the original array.