one? Method

The one? method takes an enumerable collection and tests whether the given condition is true for exactly one item in the collection.

Number List

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

# only one even number?    #=> false

# only one number 5?{|number| number == 5}    #=> true

If you've reviewed the examples for all?, any?, and none? methods, this one works in exactly the same way. It returns true if it matches EXACTLY one item in the collection; no more, no less.

Pet Inventory

# only one pet with eight legs?{|pet| pet.legs == 8}    #=> true

# only one pet with four legs?{|pet| pet.legs == 4}    #=> false

Pokey Things

# is there only one thing with the word cactus?{|thing| thing =~ /cactus/}    #=> false

# is there exactly one thing that starts with the letter p?{|thing| thing[0] == 'p'}    #=> true

Heroku Log File

# exactly one error?    #=> true

# exactly one GET request?{|request| request.method == 'GET'}    #=> false

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>