Harikrishna
Harikrishna

Reputation: 151

How can I interpolate a variable in a Ruby regex?

 data.to_enum(:scan,/(#entity[0])/i).map do |m,|
        p $`.size

How can I use dynamic variable in regular expression? #entity[0] returns a value, but in the above syntax #entity[0] is taken literally in the regex.

Upvotes: 15

Views: 6106

Answers (1)

Chowlett
Chowlett

Reputation: 46667

You want /#{entity[0]}/i. #{} is the syntax for variable insertion in strings and regexes.

Upvotes: 28

Related Questions