Charles Charles - 2 months ago 4x
Ruby Question

Allowing multiple element to work in an array

I have this array.

@stuff = ["pop", "corn", "apple", "banana"]

I wanted to make a message that would able to work anything that is included in @stuff, something like this...?

if @msg =~ /#{@stuff}/i
=> do something

I could do this way, but it would take a long time to do each single element in @stuff.

if @msg =~ /(.*)/i
if $1.to_s == "pop" #do something
elsif $1.to_s == "corn" #do something
elsif $1.to_s == "apple" #do something
elsif $1.to_s == "banana" #do something


It's really unclear what the regular expression accomplishes. You can test whether a value is in an array by simply using include?:

if @stuff.include?(msg)
  #do something

If you want to compare in a case-insensitive way, you can convert both to lower-case strings:


If you really want to use a regular expression (you shouldn't in this case), you can join the items with | and wrap them in parenthesis to produce a regular expression with a series of "OR" matches....

/(#{@stuff.join('|')})/i =~ @msg