Today you’ll learn about 4 Enumerable methods that will help you check a conditional statement against an array of elements, a hash, or any other objects that include the Enumerable module.
These 4 methods return either true or false.
Contents
Let’s do this!
Ruby All Method
If you want to check if all the strings inside an array have a specific size.
You could do this:
def all_words_have_specific_size?(words)
return false if words.empty?
words.each do |str|
return false unless str.size == 5
end
true
end
words = ["bacon", "orange", "apple"]
all_words_have_specific_size?(words)
# false
We check every string, if the size isn’t what we want we return false, otherwise we return true at the end.
That’s a lot of code for something like this.
Imagine having to set this up every time you want to do this kind of check.
It’s a lot of work!
The only thing we care about here is this:
str.size == 5
That’s the condition we are checking.
Is there a better way to do this?
Yes!
Use the all? method to do all the hard work for you.
Here’s how:
strings.all? { |str| str.size == 5 }
That’s it.
All & Empty Arrays
One thing you must know:
This all? method will return true if you call it on an empty array.
Example:
[].all? { |s| s.size == 1 }
# true
Explanation:
Since NO elements are false then all elements must be true.
That’s the logic behind this.
Ruby None Method
If you want the reverse of all?, use none?
Here’s an example:
strings.none? { |str| str.size == 5 }
This returns true if none of the strings match the condition, or false if one or more match it.
I will stick to size == 1 because it’s more explicit. Everyone will understand that even if they aren’t familiar with the one? method, which is not that common.
New Ruby 2.5 Feature
Since Ruby 2.5 these 4 methods (any? / all? / none? / one?) also take an argument which works like grep’s argument.
Just to pile on: a lot of people think that .any? checks if an enumerable contains any elements, and .none? checks if there are no elements (like .empty?). There’s a nasty gotcha lurking in that interpretation.
These don’t check whether elements exist, but whether they make the block return a truthy value (or if you don’t pass a block, then whether they are truthy). So frex [nil, false].any? is false, and [nil, false].none? is true.