How to Reject Elements from an Array in Ruby
In Ruby, you can use the
reject method on an array to remove elements that meet a certain condition. It returns a new array excluding those elements for which the block returns true. Use reject! if you want to modify the original array in place.Syntax
The reject method is called on an array and takes a block that defines the condition for rejection. Elements for which the block returns true are excluded from the returned array.
array.reject { |element| condition }- returns a new array without rejected elements.array.reject! { |element| condition }- modifies the original array by removing rejected elements.
ruby
array.reject { |element| condition }Example
This example shows how to remove all even numbers from an array using reject. The original array remains unchanged, and a new filtered array is returned.
ruby
numbers = [1, 2, 3, 4, 5, 6] filtered = numbers.reject { |num| num.even? } puts "Original array: #{numbers}" puts "Filtered array (no even numbers): #{filtered}"
Output
Original array: [1, 2, 3, 4, 5, 6]
Filtered array (no even numbers): [1, 3, 5]
Common Pitfalls
A common mistake is expecting reject to change the original array. It returns a new array instead. To modify the original array, use reject!. Also, forgetting to provide a block will cause an error.
ruby
arr = [1, 2, 3, 4] arr.reject { |x| x > 2 } puts arr.inspect # Original array unchanged arr.reject! { |x| x > 2 } puts arr.inspect # Original array modified
Output
[1, 2, 3, 4]
[1, 2]
Quick Reference
| Method | Description |
|---|---|
| reject { |e| condition } | Returns a new array excluding elements where condition is true |
| reject! { |e| condition } | Removes elements from the original array where condition is true |
| select { |e| condition } | Opposite of reject; keeps elements where condition is true |
Key Takeaways
Use
reject to get a new array excluding elements matching a condition.Use
reject! to modify the original array by removing matching elements.Always provide a block with a condition to
reject or reject!.Remember
reject does not change the original array unless you use reject!.For the opposite effect, use
select to keep elements matching a condition.