Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Reject (negative filter, grep)

  • reject

  • reject!

  • filter

  • grep

  • the reject! with the exclamation mark will modify the array

  • the reject without the exclamation mark will only return the filtered array

numbers = [10, 20, 7, 21, 5]
puts numbers
small = numbers.reject do |num|
  num > 10
end
puts small
puts numbers.reject { |num| num > 10 }
puts numbers
puts ""

big = numbers.reject! do |num|
  num < 10
end
puts big
puts numbers
[10, 20, 7, 21, 5]
[10, 7, 5]
[10, 7, 5]
[10, 20, 7, 21, 5]

[10, 20, 21]
[10, 20, 21]