Using Ruby Pathname to access relative directory

287 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 best solutions below

1
On BEST ANSWER

You need add another level like

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

now the directory name is "dir"

0
On

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

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