How to do a safe join pathname in ruby?

I recommend using File.join

>> File.join("path", "to", "join")
=> "path/to/join"

One thing to note. Ruby uses a "/" for file separator on all platforms, including Windows, so you don't actually need use different code for joining things together on different platforms. "C:/tmp/1.text" should work fine.

File.join() is your friend for joining paths together.

prefix_tmp_path = 'C:/tmp'
filename = "#{rand(10)}.txt"
fullname = File.join(prefix_tmp_path, filename) # e.g., C:/tmp/3.txt

Tags:

Ruby