YAENQ: Variable as a pattern

B

basi

(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
 
A

Adam Sanderson

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

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

enjoy,
.adam
 
J

Joel VanderWerf

basi said:
(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}]/
 
T

Timothy Hunter

basi said:
(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}/
 
B

basi

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

basi


Timothy said:
basi said:
(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}/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top