If I have a value 'Dog'
and an array ['Cat', 'Dog', 'Bird']
, how do I check this w/o looping through. Is there a simple way of checking if the value exists, nothing more?
|
You're looking for
|
|||||
|
There is no As pointed out by others, the reverse method
Note that if you have many values in your array, they will all be checked one after the other (i.e.
A quick test reveals that calling A final closing note: be wary when using |
||||
|
If you want to check by a block, you could try any? or all?.
Details are here: http://ruby-doc.org/core-1.9.3/Enumerable.html |
||||
|
There's the other way around, too! Suppose the array is [ :edit, :update, :create, :show ] - well perhaps the entire seven deadly/restful sins :) And further toy with the idea of pulling a valid action from some string - say
Solution
|
|||
|
Several answers suggest
The way to test the word presence without looping is by constructing a trie for your array. There are many trie implementations out there (google "ruby trie"). I will use
And now we are ready to test the presence of various words in your array without looping over it, in
|
|||
|