0

Given an array :

1.9.2p290 :172 >   tags_array = %w[one two]
 => ["one", "two"] 
1.9.2p290 :173 >

how can operate on it to have back (exactly) the following String ?

[/^one/i, /^two/i]

... i get a try with this :

1.9.2p290 :173 > tags_array.collect! {|tag| "/^"+tag+"/i"}
 => ["/^one/i", "/^two/i"] 
1.9.2p290 :174 > 

but I really want [/^one/i, /^two/i] without double quote.

2
  • 1
    Your expected result doesn't appear to be a string, but an array of regexps. You actual result is also an array of strings, not a string. Can you clarify? Commented May 10, 2012 at 22:28
  • forget any structure, due the first array I want a string back, the string will be composed by each element of the sourcing array, surrounded by the regexes chars (case-insensitive) ... Commented May 10, 2012 at 22:33

2 Answers 2

4

If you want an array of regexps, you can use string interpolation within a regex literal:

%w[one two].map { |tag| /^#{tag}/i }
Sign up to request clarification or add additional context in comments.

Comments

1

You have to map Regexp::new:

tag_array.collect! { |tag| Regexp.new("^#{tag}", true) }
=> [/^one/i, /^two/i]

Notice true is passed as second parameter to Regexp::new: it means the resulting regular expression should be case insensitive.

2 Comments

I get this back : 1.9.2p290 :187 > tags_array = %w[one two] => ["one", "two"] 1.9.2p290 :188 > tag_array.collect! { |tag| Regexp.new("^#{tag}", true) } => [/^(?i-mx:^(?i-mx:^one))/i, /^(?i-mx:^(?i-mx:^two))/i] 1.9.2p290 :189 >
That's because you invoked it on an Array that already contained two Regexp objects ;) My answer is just the same as the one the other user supplied, with the only difference i used the explicit constructor: try it on the ["one", "two"] array and it will work just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.