1

I'm trying to write a program which substitutes a string.

require File.join(APP_ROOT, 'lib', 'main.rb') 
files_names = Dir.entries("../DeSpacer")
files_names.each do |file_name|
  File.open("#{file_name}", "w") do |text|
  text.each {|line| line.gsub!(/\.\s{2,}/, "\.\s")}
  end
end

I keep getting a

Permission denied -. (ERRNO::EACCES)

Can you explain what I am doing wrong?

sawa
  • 165,429
  • 45
  • 277
  • 381
Ddbot
  • 13
  • 2

1 Answers1

2

The initial problem is that you're only opening the file for writing ('w'), and not reading, and thus receiving the exception.

As the comments above mention, there are other issues with the code as well.

This answer gives a more typical way to do what you're trying to do.

As mentioned in another answer to the same question, Ruby also has a command line shortcut inherited from Perl which makes things like this trivial:

ruby -pi.bak -e "gsub(/oldtext/, 'newtext')" *.txt

This will edit a file or files in place, backing up the previous version with a suffix of '.bak'.

From Programming Ruby:

-i [extension}
' Edits ARGV files in place. For each file named in ARGV, anything you write to 
standard output will be saved back as the contents of that file. A backup copy of
the file will be made if extension is supplied.
% ruby -pi.bak -e "gsub(/Perl/, 'Ruby')" *.txt
Community
  • 1
  • 1
smw
  • 592
  • 4
  • 10