Aqua Cherry
Aqua Cherry

Reputation: 1

Ruby Regular Expression issue

Here is my program:

contact_data = [
  ["[email protected]", "123 Main st.", "555-123-4567"],
  ["[email protected]", "404 Not Found Dr.", "123-234-3454"]
]

("Joe Smith").downcase #=> "joe smith"
contact_data[0][0].slice(0..2) #=> "joe"

("Joe Smith").downcase =~ /contact_data[0][0].slice(0..2)/ #=> nil

Why does my regex not show a match?

Upvotes: 0

Views: 44

Answers (1)

user229044
user229044

Reputation: 239230

You cannot embed code inside a regular expression like that.

If that worked, how could Ruby possibly know whether this regular expression...

x = 3
/x/

... was supposed to match 3 or the literal character x? How could you write a regular expression to match a simple character x if you had a variable x defined in the local scope?

If you want to embed data inside a regular expression, you need to be much more explicit. Use #{} to interpolate the value as you would with a string:

/#{contact_data[0][0].slice(0..2)}/

Upvotes: 4

Related Questions