Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, getting path from path+filename

Tags:

directory

ruby

Programming language: Ruby 1.9

Problem String: C:/Test/blah.txt
to C:/Test/

I know it's an easy question, but Google and the Ruby quickref for File have no solution for me.
And I have no experience with Regex.

like image 476
Onetimeposter123 Avatar asked Sep 13 '11 09:09

Onetimeposter123


People also ask

How do I get the full path of a file in Ruby?

Pass a string to File. expand_path to generate the path to that file or directory. Relative paths will reference your current working directory, and paths prepended with ~ will use the owner's home directory.

Where is the file path in Ruby?

Use the Ruby File. dirname method. For me, File. dirname("/a/b/c/d") correctly returns /a/b/c but File.

What is __ file __ in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.


2 Answers

Use the Ruby File.dirname method.

File.dirname("C:/Test/blah.txt") # => "C:/Test"  
like image 162
Simone Carletti Avatar answered Sep 29 '22 15:09

Simone Carletti


More versatile would be the Ruby Pathname class:

require 'pathname'  pn = Pathname.new("C:/Test/blah.txt") p pn.dirname.to_s + Pathname::SEPARATOR_LIST 

which gives C:/Test/.

like image 30
Twonky Avatar answered Sep 29 '22 16:09

Twonky