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?
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.
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
%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.
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.
You're looking for include?
:
>> ['Cat', 'Dog', 'Bird'].include? 'Dog' => true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With