using a variable as 1st param in gsub

L

louis

hi all,

i'm trying to use a user entered variable in a gsub method and for
some reason, if i insert it within a regex it doesn't work. passing it
as-is works fine. en example will be clearer:

#
#
user_variable = 'some_word' # retrieved from 'gets.chomp'
cleaned_variable = '^' + user_variable + '|\s' + user_variable + '(?!\w)'

# print out variable to see if concat worked:
puts cleaned_variable #=> prints out correct regex

p some-sentence-string.gsub(%r{cleaned_variable},'TEST') # => prints
out sentence unchanged

#---
# however if i pass it like this, it works:

p some-sentence-string.gsub(%r{user_variable},'TEST')
OR
p some-sentence-string.gsub(user_variable,'TEST')

#----

now the problem is if that variable exists within another word (e.g.
'he' matches 'hello', 'the', 'she', etc.), those match too. here's the
clincher: in irb it works as i expect. only when run inside a script
does it not work! that is, the exact same code, pasted in irb, runs
correctly.

is there something different about the parser? i thought irb just used
the same parser. what am i doing wrong? any tips for troubleshooting?
is this a bug? am i a bug?

thanks,

louis

p.s. i've also
1. concatenated '/' in the cleaned variable
2. tried to pass w/o %r{} using /cleaned_variable/ and /user_variable/
(i know, i didn't expect the latter to do anything different--just
trying anything)

p.p.s. using similar methods in python works fine (for whatever that's
worth). i haven't tried it in another language yet.

p. * 3 + s. sorry if this is a repost--i first used nabble but that
post didn't show up on any other mirror of the mailing-list, so i'm
posting again.
 
P

Phrogz

user_variable = 'some_word' # retrieved from 'gets.chomp'
cleaned_variable = '^' + user_variable + '|\s' + user_variable + '(?!\w)'

# print out variable to see if concat worked:
puts cleaned_variable  #=> prints out correct regex

p some-sentence-string.gsub(%r{cleaned_variable},'TEST') # => prints
out sentence unchanged

%r{foo} is the same as /foo/...you're using the name of the variable,
not the contents. You want:
/#{foo}/ or %r{#{foo}} or %r|#{foo}| or ...
or Regexp.new( foo )
 
L

louis

ahah! makes perfect sense. I thought interpolation in ruby using that
construct was for double quoted strings. and since it worked in irb I
was confused.
I'm not at a machine now so I can't test your suggestion but I'll
assume its correct.

thanks a lot for the help!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top