ctennis
ctennis

Reputation: 207

more succinct ruby regex

Is there are more succinct or Rubyesque way of writing this:

if ( variable =~ /regex1/ || variable =~ /regex2/ || variable =~ /regex3/ ... )
end

Namely, I'm hoping for something shorter, like:

if ( variable =~ /regex1/,/regex2/,/regex3/ )

which I realize is not valid Ruby code, but figuring someone may know a more clever trick.

Upvotes: 1

Views: 172

Answers (4)

sepp2k
sepp2k

Reputation: 370212

variable =~ Regexp.union(/regex1/, /regex2/, /regex3/)

This is assuming you can't use VoteyDisciple's which would make the most sense where it's possible.

Upvotes: 1

levi_h
levi_h

Reputation: 43

You could use a switch, or merge the expressions (if that's possible), or use a find:

if ([/regex1/, /regex2/].find {|r| v =~ r}) ...

Upvotes: 2

p00ya
p00ya

Reputation: 3709

[/regex1/,/regex2/,/regex3/].any?{|r| r =~ variable}

Upvotes: 6

VoteyDisciple
VoteyDisciple

Reputation: 37813

How about...

if ( variable =~ /regex1|regex2|regex3/ )
end

Upvotes: 5

Related Questions