Forum: Ruby best way to access directory relational to current file

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
1ed4bbef573bfc014d32356d53103ca2?d=identicon&s=25 Phil Swenson (philswenson)
on 2007-01-28 07:56
(Received via mailing list)
I'm trying to find the full path to a file. File.dirname(__FILE__)
always returns ".", which doesn't really do me any good.  The working
directory is not always the same as where the file is, so I can't use
the "." in any useful way.

What I'm trying to do is locate where a particular file is because I
know where other files are in relation to this particular file.  I
don't know what the working directory will be though, anyone could
execute the ruby file originating from any location.

Thanks for any thoughts....

phil
Aee77dba395ece0a04c688b05b07cd63?d=identicon&s=25 Daniel Berger (Guest)
on 2007-01-28 08:01
(Received via mailing list)
phil.swenson@gmail.com wrote:
> I'm trying to find the full path to a file. File.dirname(__FILE__)
> always returns ".", which doesn't really do me any good.  The working
> directory is not always the same as where the file is, so I can't use
> the "." in any useful way.

<snip>

I think you want File.expand_path(File.dirname(__FILE__))

Regards,

Dan
E0526a6bf302e77598ef142d91bdd31c?d=identicon&s=25 Daniel DeLorme (Guest)
on 2007-01-28 14:29
(Received via mailing list)
Daniel Berger wrote:
> phil.swenson@gmail.com wrote:
>> I'm trying to find the full path to a file. File.dirname(__FILE__)
>> always returns ".", which doesn't really do me any good.  The working
>> directory is not always the same as where the file is, so I can't use
>> the "." in any useful way.
>
> I think you want File.expand_path(File.dirname(__FILE__))

I tend to use this idiom a lot:
   require File.expand_path(__FILE__+'/../relative/path/to/file')

For ruby, "file" and "dummydir/../file" are considered as 2 different
files, so I think it's a good idea to always use absolute directories
when doing a require.

Daniel
This topic is locked and can not be replied to.