From: Martin DeMello Date: 2003-05-21T17:36:29+09:00 Subject: Re: How do I get a variable into a gsub? Dave Oshel wrote: > Pardon the newbie question, but I can't seem to find how to place the > contents of a variable into the regexp field of a gsub. > > That is: > > A = "There is an N such that all such N should be in parentheses, so > replace any N with (N)." > > > Ok, the specific case is trivial: > > A.gsub( / N /, " (N) " ) > > > But the general case is maddening. Obviously, I am missing something. > > > > If I try: > > B = "x" # the current thing I want to match and replace > > Then: > > A.gsub( Regexp.compile(B), " (#{B}) " ) ==> error! What error? All the following worked under 1.7.3: a.gsub(/#{b}/, "(#{b})") a.gsub(Regexp.compile(b), "(#{b})") a.gsub(Regexp.compile(b)) {|match| "(#{match})"} martin