# How to Check If Value Exists in an Array in Ruby (and Rails)

*Published on January 05, 2023*

---


If you're only using Ruby, use the&nbsp;`Array#include?`&nbsp;method to check if a value exists in an array.

[**`Array#include?(obj)`**](https://ruby-doc.org/3.2.0/Array.html#method-i-include-3F)

Returns&nbsp;`true`&nbsp;if the array includes the provided object. Otherwise, return&nbsp;`false`.

```ruby
languages = [ 'Ruby', 'Java', 'Go', 'C' ]

languages.include? 'Go'  # true

languages.include? 'C#'  # false
```

The&nbsp;`any?`&nbsp;method also accepts a block and returns&nbsp;`true`&nbsp;if any element in the array returns a truthy value.

```ruby
languages = [ 'Ruby', 'Java', 'Go', 'C' ]

languages.any? { |l| l.start_with? 'G' } # true

languages.any? { |l| l.start_with? 'F' } # false
```

[**`Object#in?(another_obj)`**](https://api.rubyonrails.org/classes/Object.html#method-i-in-3F)

If you're using Rails, the ActiveSupport library adds an&nbsp;`in?`&nbsp;method on the&nbsp;`Object`&nbsp;class, which tells you if this object is included in the other object provided in the argument.

```ruby
frameworks = [ 'Rails', 'Laravel', 'ASP.NET' ]

'Laravel'.in?(frameworks) # true

'Express'.in?(frameworks) # false
```

Let's take a peek&nbsp;[behind the scenes](https://github.com/rails/rails/blob/main/activesupport/lib/active_support/core_ext/object/inclusion.rb#L15)&nbsp;to see how the&nbsp;`in?`&nbsp;method is implemented.

```ruby
# 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&nbsp;`Range`, the&nbsp;`in?`&nbsp;method uses the&nbsp;`Range#cover?`&nbsp;method which handles open date ranges. This was a new change introduced three months ago via&nbsp;[this pull request](https://github.com/rails/rails/pull/47316).

Now, you might wonder why did Active Support introduce the&nbsp;`in?`&nbsp;method, when the&nbsp;`include?`&nbsp;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:

```ruby
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.

