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.
array.reject { |item| condition }numbers = [1, 2, 3, 4, 5] odd_numbers = numbers.reject { |n| n.even? } puts odd_numbers.inspect
words = ['apple', 'banana', 'pear'] no_a = words.reject { |w| w.include?('a') } puts no_a.inspect
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}"
reject do when called on an array?rejectreject method filters elements by removing those that satisfy the condition.select, which keeps matching elements, reject excludes them and returns a new array.reject on an array nums to remove even numbers?reject method requires a block with { |var| condition } or do |var| ... end.do syntax.arr = [1, 2, 3, 4, 5]
result = arr.reject { |x| x > 3 }
puts result.inspectx > 3 is true, so numbers 4 and 5 are removed.data. What is the error?
data = [1, nil, 2, nil, 3] clean = data.reject do |x| x = nil end puts clean.inspect
x = nil which assigns nil to x instead of checking if x equals nil.x == nil to test if x is nil for rejection.scores = { alice: 90, bob: 55, carol: 75, dave: 40 }, how can you use reject to create a new hash excluding all entries with scores below 60?score < 60.Pass the test and this pattern moves unknown