3

I want to use File.join() for building paths in Ruby:

File.Join("Dir1", "Dir2", "Dir3")

Result is:

Dir1/Dir2/Dir3

I want File.join() to uses File::ALT_SEPARATOR for doing this:

Dir1\Dir2\Dir3

How do I do this?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
  • 1
    Why do you want it to use reverse slashes? Ruby, and by extension, Rake, doesn't require them. "Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename "/gumby/ruby/test.rb" will be opened as "\gumby\ruby\test.rb". When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes: `"c:\\gumby\\ruby\\test.rb"`" – the Tin Man May 04 '15 at 15:55
  • 1
    I'd also recommend looking at Ruby's built-in [Pathname](http://ruby-doc.org/stdlib-2.2.2/libdoc/pathname/rdoc/index.html). – the Tin Man May 04 '15 at 16:00

2 Answers2

2

You could use

File.join('Dir1','Dir2').gsub(File::SEPARATOR,
     File::ALT_SEPARATOR || File::SEPARATOR)
K139
  • 3,654
  • 13
  • 17
1

You can add this function to File:

def File.join_alt(*fnames)
  sep = File::ALT_SEPARATOR || File::SEPARATOR
  fnames.map(&:to_s) # Anything with to_s
    .join(sep)       # Work on all platforms
end
Shalev Shalit
  • 1,945
  • 4
  • 24
  • 34