The one? method takes an enumerable collection and tests whether the given condition is true for exactly one item in the collection.
- View the objects used in these examples
- View these examples as a runnable ruby script on GitHub.
- Practice this method as an interactive kata on Codewars
Number List
@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8] # only one even number? @numbers.one?(&:even?) #=> false # only one number 5? @numbers.one?{|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? @inventory.one?{|pet| pet.legs == 8} #=> true # only one pet with four legs? @inventory.one?{|pet| pet.legs == 4} #=> false
Pokey Things
# is there only one thing with the word cactus? @pokey_things.seek(0) @pokey_things.one?{|thing| thing =~ /cactus/} #=> false # is there exactly one thing that starts with the letter p? @pokey_things.seek(0) @pokey_things.one?{|thing| thing[0] == 'p'} #=> true
Heroku Log File
# exactly one error? @requests.one?(&:error?) #=> true # exactly one GET request? @requests.one?{|request| request.method == 'GET'} #=> false