How to Use reject Method in Ruby: Syntax and Examples
In Ruby,
reject is a method used on collections like arrays or hashes to remove elements for which the given block returns true. It returns a new collection without those elements, leaving the original unchanged.Syntax
The reject method is called on a collection and takes a block that defines the condition to exclude elements. It returns a new collection without the elements where the block returns true.
- collection.reject { |item| condition }
- The block receives each element (or key-value pair for hashes).
- Elements making the block true are removed from the result.
ruby
array.reject { |element| element > 3 }
hash.reject { |key, value| value < 10 }Example
This example shows how to use reject to remove numbers greater than 3 from an array and key-value pairs with values less than 10 from a hash.
ruby
numbers = [1, 2, 3, 4, 5] filtered_numbers = numbers.reject { |n| n > 3 } scores = { alice: 12, bob: 8, carol: 15 } high_scores = scores.reject { |name, score| score < 10 } puts filtered_numbers.inspect puts high_scores.inspect
Output
[1, 2, 3]
{:alice=>12, :carol=>15}
Common Pitfalls
One common mistake is expecting reject to change the original collection. It returns a new collection and leaves the original unchanged. To modify the original, use reject! instead.
Another pitfall is confusing reject with select. reject removes elements where the block is true, while select keeps them.
ruby
arr = [1, 2, 3, 4] arr.reject { |x| x.even? } puts arr.inspect # Original array unchanged arr.reject! { |x| x.even? } puts arr.inspect # Original array modified
Output
[1, 2, 3, 4]
[1, 3]
Quick Reference
| Method | Description |
|---|---|
| reject | Returns a new collection excluding elements where block is true |
| reject! | Modifies the original collection by removing elements where block is true |
| select | Returns a new collection including elements where block is true |
| select! | Modifies the original collection by keeping elements where block is true |
Key Takeaways
Use
reject to get a new collection excluding elements matching a condition.reject does not change the original collection; use reject! to modify it.reject removes elements where the block returns true, opposite of select.Works on arrays and hashes, with blocks receiving elements or key-value pairs.
Always test your block condition to avoid unexpected filtering results.