ccg
ccg

Reputation: 313

Ruby - replacing string via gsub and regexp

How can I replace the string 'nEEdle' to get the following result:

"haystackhaystacknEEdlehaystack" -> "haystackhaystack<b>nEEdle</b>haystack"

In my application I have the search parameter only in lowercase, so I want to take the last regexp result ($~) and use it as the replacement string. The following approach doesn't work:

n = "needle"
haystack.gsub(/#{n}/i, "<b>#{$~}</b>")

Any hints?

Upvotes: 1

Views: 215

Answers (1)

xdazz
xdazz

Reputation: 160843

Try:

heystack.g­sub(/#{n}/­i, '<b>\0</b>')

Upvotes: 5

Related Questions