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?
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.
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
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 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.
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.
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.
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