SupremeA
SupremeA

Reputation: 1621

Check if a string is any of multiple items

I have a string

x = "student"

how do I check if "x" matches any of the items in a list of names that I have. The names are a fixed list.

names = ["teacher", 
         "parent", 
         "son", 
         "daughter", 
         "friend", 
         "classmate", 
         "principal", 
         "vice-principal", 
         "student", 
         "graduate"]

I tried setting names as a list and using any? to check the list but that seems to only work for an array and I have a string.

I am using Ruby 2.2.1 Also I only need it to return true or false if the item is in the list

Upvotes: 0

Views: 796

Answers (5)

Wand Maker
Wand Maker

Reputation: 18772

Here is one more way to do this:

if not (names & [x]).empty?
  puts "'#{x}' is present in names"
end

Upvotes: 0

rohin-arka
rohin-arka

Reputation: 799

You can also use grep for finding string is present in an array or not

names = ["teacher", 
         "parent", 
         "son", 
         "daughter", 
         "friend", 
         "classmate", 
         "principal", 
         "vice-principal", 
         "student", 
         "graduate"]

names.grep(/^daughter$/)

Upvotes: 1

Sagar Pandya
Sagar Pandya

Reputation: 9508

What if your names array contains multiple instances of x? Then assuming you're not after a boolean you could use Enumerable#count where we pass the condition required within a code block. In your example we would have:

names.count{ |i| i == x } #=> 1 

Another example:

x = "student"
names = ["student", "cleaner", "student"] 

names.count{ |i| i == x } #=> 2 

Upvotes: 0

Shimu
Shimu

Reputation: 1147

names.include?(your_string)

If the string is inside the array it will return true

Upvotes: 3

Daniel Christiany
Daniel Christiany

Reputation: 227

You can use the include? method on array like so:

if names.include? x do
  # x is an element in the list
end

Upvotes: 1

Related Questions