Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I interpolate a variable in a Ruby regex?

Tags:

regex

ruby

 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.

like image 901
Harikrishna Avatar asked Jul 17 '11 05:07

Harikrishna


People also ask

What is interpolation in Ruby?

String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals.

How does regex work in Ruby?

Two uses of ruby regex are Validation and Parsing. Ruby regex can be used to validate an email address and an IP address too. Ruby regex expressions are declared between two forward slashes. This will return the index of first occurrence of the word 'hi' if present, or else will return ' nil '.

What character do you wrap interpolation with?

These interpolations are wrapped in ${} , such as ${var. foo} . The interpolation syntax is powerful and allows you to reference variables, attributes of resources, call functions, etc. You can also perform simple math in interpolations, allowing you to write expressions such as ${count.

What does string interpolation do?

String interpolation is a technique that enables you to insert expression values into literal strings. It is also known as variable substitution, variable interpolation, or variable expansion. It is a process of evaluating string literals containing one or more placeholders that get replaced by corresponding values.


1 Answers

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

like image 127
Chowlett Avatar answered Oct 04 '22 16:10

Chowlett