YAENQ: Variable as a pattern

(basi) #1

(I ordered for a copy of Mastering Regular Expressions. Should be in my
snail mailbox anytime soon. In the meantime ... )

How do I tell Ruby to use the content of a variable as the pattern,
rather than interpreting the variable name as a literal?

v = "aeiou"

Then, in

"goodness" =~ /[v]/

I'd like v to be interepreted not as a literal but as a variable name.

Thanks
basi

(Adam Sanderson) #2

String interpolation seems to work on regular expressions so try:
"goodness" =~ /[#{v}]/

Or more verbosely:
"goodness" =~ Regexp.new("[#{v}]")

enjoy,
  .adam

(Joel VanderWerf) #3

basi wrote:

(I ordered for a copy of Mastering Regular Expressions. Should be in my
snail mailbox anytime soon. In the meantime ... )

How do I tell Ruby to use the content of a variable as the pattern,
rather than interpreting the variable name as a literal?

v = "aeiou"

Then, in

"goodness" =~ /[v]/

I'd like v to be interepreted not as a literal but as a variable name.

Same as with a string:

"goodness" =~ /[#{v}]/

···

--
      vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

(Tim Hunter) #4

basi wrote:

(I ordered for a copy of Mastering Regular Expressions. Should be in my
snail mailbox anytime soon. In the meantime ... )

How do I tell Ruby to use the content of a variable as the pattern,
rather than interpreting the variable name as a literal?

v = "aeiou"

Then, in

"goodness" =~ /[v]/

I'd like v to be interepreted not as a literal but as a variable name.

Thanks
basi

"goodness" =~ /#{v}/

(basi) #5

thanks to all who replied. so simple. (goodness, why didn't I think of
that. sigh.)

basi

Timothy Hunter wrote:

···

basi wrote:
> (I ordered for a copy of Mastering Regular Expressions. Should be in my
> snail mailbox anytime soon. In the meantime ... )
>
> How do I tell Ruby to use the content of a variable as the pattern,
> rather than interpreting the variable name as a literal?
>
>
> v = "aeiou"
>
> Then, in
>
> "goodness" =~ /[v]/
>
> I'd like v to be interepreted not as a literal but as a variable name.
>
> Thanks
> basi
>

"goodness" =~ /#{v}/