When to use Regexp.new()?
regex, ruby
Solution
Let's imagine you want to make your system detect "a sentence that starts with DOG and ends with CAT". Obvious Regex would be something like `/DOG.+CAT\./`[1].
So far, works. But now you'd like to be able to enhance the system, so the user can configure the opening and closing words. You might be able to do it with `//` syntax and interpolation:
/#{startWord}.+#{endWord}\./
but you also can do it with simple strings:
Regex.new(startWord + ".+" + endWord + "\.")
Cosmetics. Use what you like the most. However, there is one more thing that's important. With the `new` function, you can pass not only one, but also more parameters. See the docs.
So, the main[2] purpose of the existence of `new` from your point is actually being able to pass more arguments than just one. With `//` you can only pass the regex-formula[3]. With `new` you can pass options.
Few details were oversimplified for clarity. [1] It is not a valid "sentence detector". It is only some regex to show the problem. [2] It's not main purpose. The `new` is a constructor. It must exist or we would not be able to construct the object. Actually, the `/blargh/` syntax is translated into a `new` call. [3] Actually, with `//` you can pass some options too, like `/CaSEiNseNsiTive/i`. But, well, constructors are still more flexible.
Problem
I couldn't find any proper answer as Regexp stands for Regular Expressions. Here is an example: ``` test = Regexp.new("Hello") ``` It returns `/Hello/`, but I'm confused over the use of this. Why not use `/Hello/` directly? Can anyone give me a small example of `Regexp.new()` function?