0
0
Rubyprogramming~5 mins

Reject for inverse filtering in Ruby

Choose your learning style9 modes available
Introduction
Rejecting items helps you remove unwanted things from a list based on a rule. Inverse filtering means keeping only those items that do NOT match the rule.
When you want to remove all even numbers from a list and keep only odd numbers.
When you want to filter out all words that contain a certain letter.
When you want to exclude all users under 18 years old from a list.
When you want to remove all empty strings from a list of words.
Syntax
Ruby
array.reject { |item| condition }
The block inside reject returns true for items to remove.
Reject returns a new array without the rejected items.
Examples
Removes even numbers, keeps odd numbers.
Ruby
numbers = [1, 2, 3, 4, 5]
odd_numbers = numbers.reject { |n| n.even? }
puts odd_numbers.inspect
Removes words containing letter 'a'.
Ruby
words = ['apple', 'banana', 'pear']
no_a = words.reject { |w| w.include?('a') }
puts no_a.inspect
Sample Program
This program removes fruits that contain the letter 'a' and shows both lists.
Ruby
fruits = ['apple', 'banana', 'cherry', 'date']
# Remove fruits that have the letter 'a'
filtered = fruits.reject { |fruit| fruit.include?('a') }
puts "Original: #{fruits.inspect}"
puts "Filtered: #{filtered.inspect}"
OutputSuccess
Important Notes
Reject is the opposite of select, which keeps items matching the condition.
Reject does not change the original array unless you use reject! with an exclamation mark.
Summary
Use reject to remove items matching a condition.
It returns a new array without those items.
Great for filtering out unwanted elements easily.