Neil Hoff
Neil Hoff

Reputation: 2085

Ruby: Dir.chdir using data from a text file in windows

I am trying to use a script to change the working directory using Dir.chdir

This works:

dirs = ['//servername/share','//servername2/share']

dirs.each do |dir|
  Dir.chdir dir
end

If I put the above share information into a text file (each share on a new line) and try to load:

File.foreach("shares.txt") {|dir|
  Dir.chdir dir
}

I get this error:

'chdir': No such file or directory - //servername/share (Errno::ENOENT)

How can I read the shares from a text file and change to that directory? Is there a better way to do this?

Upvotes: 2

Views: 1203

Answers (1)

knut
knut

Reputation: 27875

Try

Dir.chdir dir.strip

or

Dir.chdir dir.chomp

Reason: With File.foreach you get lines including a newlines (\n).

strip will delete leading and trailing spaces, chomp will delete trailing newlines.


Another possibility: In your example you use absolute paths. This should work.

If you use relative paths, then check, in which directory you are (you change it!). To keep the directory you may use the block-version of Dir.chdir.

Upvotes: 6

Related Questions