What if you could remove unwanted items from a list with just one simple line of code?
Why Reject for inverse filtering in Ruby? - Purpose & Use Cases
Imagine you have a big list of fruits, and you want to remove all the ones that are red. Doing this by checking each fruit one by one and writing extra code to skip the red ones can get confusing and take a lot of time.
Manually checking each item and removing unwanted ones means writing long loops and many if-else checks. This is slow, easy to mess up, and hard to read. If the list changes, you have to rewrite your code again.
Using reject lets you say exactly what you want to leave out in a simple, clear way. It automatically goes through the list and removes items that match your condition, making your code shorter and easier to understand.
filtered = [] for fruit in fruits if fruit.color != 'red' filtered << fruit end end
filtered = fruits.reject { |fruit| fruit.color == 'red' }You can quickly and clearly remove unwanted items from collections without messy loops or extra variables.
Suppose you have a list of users and want to exclude those who are inactive. Using reject makes it easy to filter them out in one line.
Manual filtering is slow and error-prone.
reject simplifies removing unwanted items.
Code becomes cleaner, shorter, and easier to maintain.