Morton Goldberg
7/18/2006 2:13:00 AM
I take it you are referring to ruby code such as:
FOLDER = "#{ENV['HOME']}/Desktop/" # or whatever folder you want
INFILE = "input.txt"
OUTFILE = "output.txt"
old = File.read(FOLDER + INFILE) # read file in as one big string
old.gsub!(/\bsearch\b/, "replace") # do in-place substitution
File.open(FOLDER + OUTFILE, "w") {|new| new.write(old)} # write
modified text out to disk.
This code does not open "input.txt" in RW mode nor modify it in
place. For one thing, gsub! only works on strings not file objects.
For another, I'm too nervous to do that kind of thing. Of course, if
INFILE == OUTFILE, it would overwrite "input.txt".
In general, it is a naming convention that a method ending in !
signifies that the method does in-place (destructive) modification to
the receiver. I first ran into this convention when studying scheme
back in the 1980s. I don't know if has any history beyond that.
Schemers would read gsub! as GEE-SUB-BANG. I'm new to ruby, too, so
I'm not sure if rubyists read it the same way.
Regards, Morton
On Jul 17, 2006, at 9:19 PM, Xavier Hanin wrote:
> Hi all,
>
> I'm brand new to ruby, and I'm looking for a way to open a file, read
> its content and modify it. I've seen that I can open a file in read
> write mode, but I can't figure out how it works. If I want to replace
> all occurences of 'search' by 'replace', for instance, what do I
> have to
> do?
>
> Searching for an answer to this question, I've found scripts using
> gsub!
> What is this exclamation mark?
>
> Thanks in advance for your help!
>
> Xavier