Check if a value exists in an array in Ruby

ruby check if array contains object with attribute
ruby array not include
ruby array find
ruby check if array is not empty
ruby check if array exists
value exists in array ruby
ruby if value exists in array
exist in array ruby

I have a value 'Dog' and an array ['Cat', 'Dog', 'Bird'].

How do I check if it exists in the array without looping through it? Is there a simple way of checking if the value exists, nothing more?

You're looking for include?:

>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

Learn Ruby, Learn Ruby – How To Check if A Value Exists in An Array? August 26, 2016. In Ruby, as in other programming languages, an array is a list of items with an order​  In Ruby, as in other programming languages, an array is a list of items with an order within your code. Each item has its position in this list and acts as a variable: you can see which object points to a given position, and you can make it point to a different object.

There is an in? method in ActiveSupport (part of Rails) since v3.1, as pointed out by @campaterson. So within Rails, or if you require 'active_support', you can write:

'Unicorn'.in?(['Cat', 'Dog', 'Bird']) # => false

OTOH, there is no in operator or #in? method in Ruby itself, even though it has been proposed before, in particular by Yusuke Endoh a top notch member of ruby-core.

As pointed out by others, the reverse method include? exists, for all Enumerables including Array, Hash, Set, Range:

['Cat', 'Dog', 'Bird'].include?('Unicorn') # => false

Note that if you have many values in your array, they will all be checked one after the other (i.e. O(n)), while that lookup for a hash will be constant time (i.e O(1)). So if you array is constant, for example, it is a good idea to use a Set instead. E.g:

require 'set'
ALLOWED_METHODS = Set[:to_s, :to_i, :upcase, :downcase
                       # etc
                     ]

def foo(what)
  raise "Not allowed" unless ALLOWED_METHODS.include?(what.to_sym)
  bar.send(what)
end

A quick test reveals that calling include? on a 10 element Set is about 3.5x faster than calling it on the equivalent Array (if the element is not found).

A final closing note: be wary when using include? on a Range, there are subtleties, so refer to the doc and compare with cover?...

Ruby Array exercises: Check whether a value exists in an array , Ruby Array exercises, Practice and Solution: Write a Ruby program to check whether a value exists in an array. Previous: Ruby Basic Exercises Next: Write a Ruby program to check whether 7 appears as either the first or last element in an given array. The array length must be 1 or more.

Try

['Cat', 'Dog', 'Bird'].include?('Dog')

How to test if array element exists? - Ruby, I'm new to Ruby and just want to test if an array element exists. Here's a basic the element does not exist in the array, not the actual value. Notice the little * in the when clause, this checks for membership in the array. All the usual magic behavior of the splat operator applies, so for example if array is not actually an array but a single element it will match that element. | this answer answered Dec 25 '16 at 23:48 akuhn 20.1k 2 43 65

Use Enumerable#include:

a = %w/Cat Dog Bird/

a.include? 'Dog'

Or, if a number of tests are done,1 you can get rid of the loop (that even include? has) and go from O(n) to O(1) with:

h = Hash[[a, a].transpose]
h['Dog']


1. I hope this is obvious but to head off objections: yes, for just a few lookups, the Hash[] and transpose ops dominate the profile and are each O(n) themselves.

include? (Array), Ruby latest stable (v2_5_5) - 5 notes - Class: Array Returns true if the given object is present in self (that is, if any element == object), long i; VALUE e; for (i​=0; i<RARRAY_LEN(ary); i++) { e = RARRAY_AREF(ary, i); if You can just use a set difference (aka minus) to see if one array includes all elements of another How to check if a given directory exists in Ruby. Ask Question Asked 10 years, 9 months ago. How to check if a value exists in an array in Ruby. 1049.

If you want to check by a block, you could try any? or all?.

%w{ant bear cat}.any? {|word| word.length >= 3}   #=> true  
%w{ant bear cat}.any? {|word| word.length >= 4}   #=> true  
[ nil, true, 99 ].any?                            #=> true  

Details are here: http://ruby-doc.org/core-1.9.3/Enumerable.html My inspiration come from here: https://stackoverflow.com/a/10342734/576497

Learn How to Use Ruby Arrays in Less Than 10 Minutes, Check if a value exists. There are a few ways you might want to check for values. The first and most obvious is to see if an element exists at a  While the answers are concerned with looking through the array to see if a particular string or object exists, that's really going about it wrong, because, as the array gets larger, the search will take longer. Instead, use either a Hash, or a Set. Both only allow a single instance of a particular element.

How to Check if a Value Exists in a Set of Nested Hashes in Ruby, Summary. Build a method that looks through an array of hashes to see if a value exists anywhere inside of one of the hashes. In Ruby on Rails Programming you might have to check if key exists in hash and based on that you might have to perform other operation. There is a simple way to detect if key exists in particular hash. Ruby hash contains Key-Value pairs. In Ruby, you can create a simple hash as follows, my_hash = {}.

How To Determine If An Array Contains Any Value From Another , How To Determine If An Array Contains Any Value From Another Array In Ruby. Posted by Weston Ganger. The sort method takes a Ruby block that gives you access to elements in the array so you can compare them. To do the comparison, you use the comparison operator ( <=> ), often referred to as the spaceship operator. This operator compares two Ruby objects and returns -1 if the object on the left is smaller,

How to Use Ruby Any, All, None & One, 1 Ruby All Method; 2 All & Empty Arrays; 3 Ruby None Method; 4 Ruby Any If you want to check if all the strings inside an array have a specific size. a block to check if the array contains exactly one truthy value (anything but false / nil ). elements exist, but whether they make the block return a truthy value (or if you  You can also convert an array to a string, transform one array of data into another, and roll up an array into a single value. In this tutorial, you'll explore some of the most practical methods Ruby provides for working with data stored in arrays.

Comments
  • use the .include? method. It returns a boolean which is what you want. In your case just type: ['Cat', 'Dog', 'Bird'].include('Dog') and it should return the boolean true.
  • dont use include? method if you want to check multiples times for different value to be present in array or not because include? each time will iterate over array taking O(n) operation to search each time, Instead make a hash hash = arr.map {|x| [x,true]}.to_h, now check whether hash.has_key? 'Dog' returns true or not
  • You can't really do it totally "without looping through it". It's logically impossible, the computer just can't know for sure whether the array contains the element without looping through the elements to check if any of them are the one it is searching for. Unless it's empty, of course. Then I guess you don't need a loop.
  • Alternate syntax: %w(Cat Dog Bird).include? 'Dog'
  • Sometimes I wish it was "contains" not include. I always get it mixed up with includes.
  • Let me just note that internally, #include? still does perform looping. The coder is saved from writing the loop explicitly, though. I have added an answer that performs the task truly without looping.
  • @HenleyChiu I which it was called [ 'Dog', 'Bird', 'Cat' ].has? 'Dog'
  • @AlfonsoVergara Yes, any solution for an array must do some sort of looping internally; there is no way to test for membership of an array without looping. If you don't want to do any looping even internally, you need to use a different data structure, such as a perfect hash table with fixed sized keys. Given that there's no way to test for membership in an array without looping internally, I interpreted the question to mean "without having to write the loop explicitly myself"
  • While Ruby doesn't include #in? in it's core, if you are using Rails, it is available. api.rubyonrails.org/classes/Object.html#method-i-in-3F (I know this is a Ruby, not a Rails question, but it may help anyone looking to use #in? in Rails. Looks like it was added in Rails 3.1 apidock.com/rails/Object/in%3F
  • this is the older syntax, look ^^^ @brian's answer
  • @jahrichie what exactly do you consider "older syntax" in this answer, the optional parentheses?
  • i agree @Dennis , this is not older, parentheses are optional and in most of the cases a GOOD PRACTICE.... try using include without parentheses in a one line if sentence for instance, what i meant is that depending on your case you should or must use brackets or not (not related with "old" ruby syntaxes at all)
  • This is the only syntax I could get to work within a ternary operation.