0

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'.

thisismydesign
  • 21,553
  • 9
  • 123
  • 126
  • `p.to_s`; `p.basename.to_s` – Petr Skocik Jun 23 '15 at 11:16
  • Obviously, I'm working on a generic solution that also needs to handle directories on base level. In a normal case dirname works fine (/etc/dir/file => /etc/dir) this is why I want to use that. to_s and basename make no sense in this case. The question clearly states my purpose, please do not downvote and give unrelated answers. – thisismydesign Jun 23 '15 at 11:27
  • You want to use `dirname` to return something that's not the directory name? You need add another level like `p = Pathname.new('dir/.')` now the directory name is "dir" – John La Rooy Jun 23 '15 at 11:31
  • Dirname returns what directory 'dir/' is in. I don't think what you're asking is very clear. – Petr Skocik Jun 23 '15 at 11:34
  • @John La Rooy: IMO 'dir/' clearly is a directory. But if it is not posibble wihtout addig another level then that answers my question, thank you. I'll accept your answer if you post it. – thisismydesign Jun 23 '15 at 11:36
  • @PSkocik: I wanted to refer to dir as directory without adding another level (since I don't know what is inside), but '.' makes sense. – thisismydesign Jun 23 '15 at 11:42

2 Answers2

2

You need add another level like

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

now the directory name is "dir"

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

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

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

David K
  • 692
  • 10
  • 23