If you're only using Ruby, use the Array#include?
method to check if a value exists in an array.
Returns true
if the array includes the provided object. Otherwise, return false
.
languages = [ 'Ruby', 'Java', 'Go', 'C' ]
languages.include? 'Go' # true
languages.include? 'C#' # false
The any?
method also accepts a block and returns true
if any element in the array returns a truthy value.
languages = [ 'Ruby', 'Java', 'Go', 'C' ]
languages.any? { |l| l.start_with? 'G' } # true
languages.any? { |l| l.start_with? 'F' } # false
If you're using Rails, the ActiveSupport library adds an in?
method on the Object
class, which tells you if this object is included in the other object provided in the argument.
frameworks = [ 'Rails', 'Laravel', 'ASP.NET' ]
'Laravel'.in?(frameworks) # true
'Express'.in?(frameworks) # false
Let's take a peek behind the scenes to see how the in?
method is implemented.
# active_support/core_ext/object/inclusion.rb
def in?(another_object)
case another_object
when Range
another_object.cover?(self)
else
another_object.include?(self)
end
rescue NoMethodError
raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
end
When the provided object is a Range
, the in?
method uses the Range#cover?
method which handles open date ranges. This was a new change introduced three months ago via this pull request.
Now, you might wonder why did Active Support introduce the in?
method, when the include?
works perfectly fine? The answer can be found in the Rails Doctrine:
Sometimes beautiful code is more subtle, though. It’s less about making something as short or powerful as possible, but more about making the rhythm of the declaration flow.
These two statements do the same:
if people.include? person
...
if person.in? people
In the first statement, the focus is on the collection. That’s our subject. In the second statement, the subject is clearly the person. There’s not much between the two statements in length, but I’ll contend that the second is far more beautiful and likely to make me smile when used in a spot where the condition is about the person.
Indeed.