Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, how do I find out if a string is not in an array?

Tags:

arrays

ruby

In Ruby, how would I return true if a string is not in an array of options?

# pseudo code do_this if current_subdomain not_in ["www", "blog", "foo", "bar"] 

...or do you know of a better way to write this?

like image 788
Andrew Avatar asked Apr 16 '11 02:04

Andrew


People also ask

How do you check if a string exists in an array Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.

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.

How do you check if an array contains an element in 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.

Do you know how do you split a string sentence into an array of words Ruby?

The general syntax for using the split method is string. split() . The place at which to split the string is specified as an argument to the method. The split substrings will be returned together in an array.


2 Answers

do_this unless  ["www", "blog", "foo", "bar"].include?(current_subdomain) 

or

do_this if not ["www", "blog", "foo", "bar"].include?(current_subdomain) 

I'm using the Array#include? method.

However using unless is a fairly big ruby idiom.

like image 191
Mike Lewis Avatar answered Oct 05 '22 07:10

Mike Lewis


You can try exclude? method instead of include?

Example:

do_this if ["www", "blog", "foo", "bar"].exclude?(current_subdomain) 

Hope this help...Thanks

Edited: This function is applicable only for Rails (ActiveSupport), not native Ruby.

like image 43
Amol Udage Avatar answered Oct 05 '22 05:10

Amol Udage