reject method

The reject method works the opposite of the select method; it takes an enumerable collection and returns a new array of the elements for which the given block returns false.

Number List

@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

# all odd numbers:
@numbers.reject(&:even?)
    #=> [1, 3, 5, 7, 9]

# all negative numbers:
@numbers.reject{|number| number >= 0}
    #=> []

Pet Inventory

# all pets without legs:
@inventory.reject{|pet| pet.legs > 0}.map(&:name)
    #=> ["fish", "rock"]

# all pets out of stock:
@inventory.reject(&:in_stock?).map(&:name)
    #=> ["rock"]

# all pets without a name:
@inventory.reject{|pet| !pet.name.nil?}.map(&:name)
    #=> []

Pokey Things

# pokey things without at least 5 letters:
@pokey_things.seek(0)
@pokey_things.reject{|line| line.chomp.size >= 5}.map(&:chomp)
    #=> ["pole"]

# pokey things without the letter 'e':
@pokey_things.seek(0)
@pokey_things.reject{|line| line.include?('e')}.map(&:chomp)
    #=> ["cactus"]

Heroku Log File

# all heroku requests NOT made via the GET method:
@requests.reject(&:get?).map(&:id)
    #=> [22]

# all heroku requests NOT made via the POST method:
@requests.reject(&:post?).map(&:id)
    #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31]

Leave a Reply

Your email address will not be published. Required fields are marked *