Scan - variable as pattern

I want to define a variable, like:
s=’.’

And then use that variable as an argument for scan

str.scan(/s/)

In the above I want the . substituted for s.

Is there any way this can be done - pass a variable to scan?

Thanks

You can interpolate regular expressions just as you would strings:

str.scan(/#{s}/)

The docs for rRegexp (http://www.ruby-doc.org/core-1.9.3/Regexp.html)
have a example
you need str.scan /#{s}/

cheers

On Mon, Dec 26, 2011 at 4:23 AM, Chris H. [email protected]
wrote:

The docs for rRegexp (http://www.ruby-doc.org/core-1.9.3/Regexp.html)
have a example
you need str.scan /#{s}/

I’d prefer to pass a Regexp instance directly in the variable:

any of these will do

r = /./
r = Regexp.new ‘.’
r = /#{s}/

str.scan r do |match|

end

Cheers

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs