Luca G. Soave
Luca G. Soave

Reputation: 12709

String manipulation in Ruby

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.

Upvotes: 0

Views: 340

Answers (2)

Pete
Pete

Reputation: 11505

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

%w[one two].map { |tag| /^#{tag}/i }

Upvotes: 4

Alberto Moriconi
Alberto Moriconi

Reputation: 1655

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.

Upvotes: 1

Related Questions