Take the 2-minute tour ×

I'm having a problem with getting a Ruby string substitution going. I'm writing a preprocessor for a limited language that I'm using, that doesn't natively support arrays, so I'm hacking in my own.

I have a line:

x[0] = x[1] & x[1] = x[2]

I want to replace each instance with a reformatted version:

x__0 = x__1 & x__1 = x__2

The line may include square brackets elsewhere.

I've got a regex that will match the array use:

array_usage = /(\w+)\[(\d+)\]/

but I can't figure out the Ruby construct to replace each instance one by one. I can't use .gsub() because that will match every instance on the line, and replace every array declaration with whatever the first one was. .scan() complains that the string is being modified if you try and use scan with a .sub()! inside a block.

Any ideas would be appreciated!

share|improve this question
add comment

1 Answer

up vote 11 down vote accepted

Actaully you can use gsub, you just have to be careful to use it correctly:

s = 'x[0] = x[1] & x[1] = x[2]'
s.gsub!(/(\w+)\[(\d+)\]/, '\1__\2')
puts s


x__0 = x__1 & x__1 = x__2
share|improve this answer
Oh, magic, thank you. This wasn't working for me because I wrapped the '\1__\2' in double-quotes "", not single ''. I will go and read up why Ruby treats each one differently. Thanks Mark! –  cflewis Mar 27 '10 at 22:41
@Lewisham: When you use double-quotes "\1" is interpreted as the escape code for ASCII character 1. When you use single quotes, the string is interpreted literally as a backslash followed by 1, which gsub recognises. –  Mark Byers Mar 27 '10 at 22:46
add comment

Your Answer


