Trouble with pathname (i.e slashes) & windows

Hi,

I am a bit of a ruby newbie, and i cant figure out this problem. I am
recursively searching through some directories, and when i find the
one i want, i try to pass it to an external process, through ‘system’
but the forward slashes screw things up.

i tried replacing the forward slashes through gsub, but i end up with
2 slashes. for example, if i am trying to ‘dir’ a path, this ends up
being sent through system:

dir c:\myStartDir/currentDir #obviously this wont work, so i tried
using gsub, and i get this

dir c:\myStartDir\currentDir #and ‘dir’ complains it cant find the
directory.

my code looks something like this

dirPath = File.dirname(path).gsub(’/’, “\”)
system("dir " + dirPath)

path is determined using Find.find(c:\myStartDir)

any help is greatly appreciated. Thanks!

On 9/27/07, [email protected] [email protected] wrote:

path is determined using Find.find(c:\myStartDir)

any help is greatly appreciated. Thanks!

I use path.gsub(File::SEPARATOR, File::ALT_SEPARATOR) for the
conversion.
But I don’t think that’s your problem.

How did you print those paths? For me Find.find(“c:\ruby”) {|f| puts
f.gsub(’/’, “\”)}
works fine. Can you replace system("dir " + dirPath ) with puts ("dir
" + dirPath) to see the output? If you use p to print values, it will
escape special chars, therefore slashes will be doubled. The same in
irb. Or, replace "dir " with "echo dir " and see the result.

I guess you should test dirPath whether it’s a directory. ()

system("dir " + dirPath) if File.directory? dirPath

or better still,

if File.directory? path
dirPath = File.dirname(path).gsub(’/’, “\”)
system("dir " + dirPath)
end

Jano

On 9/26/07, [email protected] [email protected] wrote:

Hi,

I am a bit of a ruby newbie, and i cant figure out this problem. I am
recursively searching through some directories, and when i find the
one i want, i try to pass it to an external process, through ‘system’
but the forward slashes screw things up.

Your best bet is probably to follow these rules:

  1. Inside Ruby (meaning, anywhere but between two backtick characters
    or in the ‘system’ method), always use forward-slashes.

  2. When calling out to the system, do this:

class String
def nightmareify
self.gsub(///, ‘\\’)
end
end

irb> puts “c:/foo/baz”.nightmareify
c:\foo\baz

Feel free to choose a different method name, depending on your level
of irritation at this:
http://blogs.msdn.com/larryosterman/archive/2005/06/24/432386.aspx

I figured out my problem…turns out that my path had spaces in the
name, and i forgot to surround the path with quotations. Kinda dumb,
but its not one of those things you think of immediately.

thanks!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs