Using Ruby Pathname to access relative directory

266 views Asked by At

Given I have a relative path pointing to a directory how can I use it with Ruby's Pathname or File library to get the directory itself?

p = Pathname.new('dir/')

p.dirname => .

p.directory? => false

I have tried './dir/', 'dir/', 'dir'.

What I want is p.dirname to return 'dir'. I do not want point to another file or directory within 'dir'.

2

There are 2 answers

1
John La Rooy On BEST ANSWER

You need add another level like

p = Pathname.new('dir/.') 

now the directory name is "dir"

0
David K On

File.expand_path(FILE) => "/tmp/somefile"

File.dirname(File.expand_path(FILE)) => "/tmp"