[#6363] Re: rescue clause affecting IO loop behavior — ts <decoux@...>

>>>>> "D" == David Alan Black <dblack@candle.superlink.net> writes:

17 messages 2000/11/14
[#6367] Re: rescue clause affecting IO loop behavior — David Alan Black <dblack@...> 2000/11/14

Hello again --

[#6582] best way to interleaf arrays? — David Alan Black <dblack@...>

Hello --

15 messages 2000/11/26

[#6646] RE: Array Intersect (&) question — Aleksi Niemel<aleksi.niemela@...>

Ross asked something about widely known and largely ignored language (on

23 messages 2000/11/29
[#6652] RE: Array Intersect (&) question — rpmohn@... (Ross Mohn) 2000/11/29

aleksi.niemela@cinnober.com (Aleksi Niemel) wrote in

[#6723] Re: Array Intersect (&) question — Mathieu Bouchard <matju@...> 2000/12/01

> >Use a hash. Here's code to do both and more. It assumes that

[#6656] printing/accessing arrays and hashes — raja@... (Raja S.)

I'm coming to Ruby with a Python & Common Lisp background.

24 messages 2000/11/30

[ruby-talk:6441] Re: variable in regular expression

From: Dave Thomas <Dave@...>
Date: 2000-11-18 17:01:13 UTC
List: ruby-talk #6441
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

In This Thread