Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a value exists in an array in Ruby

Tags:

arrays

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?

like image 865
user211662 Avatar asked Dec 31 '09 17:12

user211662


People also ask

How do you check if a value is in an array Ruby?

To check if a value is in the array, you can use the built-in include? method. The include? method returns true if the specified value is in the array and false if not.

How do you check if an element is present in an array or not?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

What is %W in Ruby?

%w(foo bar) is a shortcut for ["foo", "bar"] . Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.

What does .first do in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


1 Answers

You're looking for include?:

>> ['Cat', 'Dog', 'Bird'].include? 'Dog' => true 
like image 71
Brian Campbell Avatar answered Oct 23 '22 03:10

Brian Campbell