markus jais <mjais / web.de> writes:

> hello,
> 
> I have recently bought the new book about ruby and are new trying to learn.
> I have one question about variable in regular expressions
> 
> I have a little script which I want to use to rename files in a directory:
> the code is a follows:
> 
> old = ARGV[1]
> new = ARGV[2]
> dir = Dir.new(".");
> while line = dir.read
>   next if line == "." or line == ".."
>   puts line
>   line.sub!(/old/,  new)    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Error
>   puts line
> end

Two things:

Firstly, you don't need the //'s in the call to sub. It works out that 
you want to convert the string to a regexp, and does it for you. If
you _did_ want to substitute the variable in, you'd use /#{old}/.

Secondly (and perhaps you mean this the way it is, in which case just
ignore me) the first argument to your program is ARGV[0], and the
second ARGV[1].

Also, you could make the program more efficient by generating the
regular expression just once:

   old = Regexp.new(ARGV[0])


And... if you didn't need the power of regular expressions, but were
just substituting one string for another, you could use

   line[old] = new


Regards


Dave