Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awesome/8674666 to your computer and use it in GitHub Desktop.
Save awesome/8674666 to your computer and use it in GitHub Desktop.
how to get the directory of the current file using ruby #soawesomeman
# UPDATE: Ruby 2.0.0 https://docs.ruby-lang.org/en/2.0.0/Kernel.html#method-i-__dir__
# $ ruby -v
# ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin18]
# $ pwd
# /Users/dev/Documents/Github/Gists/awesome/
# $ echo "puts __dir__" > how-to-get-the-directory-of-the-current-file-using-ruby-2-0-0.rb
# $ cat how-to-get-the-directory-of-the-current-file-using-ruby-2-0-0.rb
# puts __dir__
# $ ruby how-to-get-the-directory-of-the-current-file-using-ruby-2-0-0.rb
# /Users/dev/Documents/Github/Gists/awesome/
#######################################
# NOTICE: For Ruby versions older than 2.0.0, see below:
#
#__FILE__
# => "how-to-get-the-directory-of-the-current-file-using-ruby.rb"
# File.dirname(__FILE__)
# => "."
# File.expand_path(File.dirname(__FILE__))
# => "/Users/dev/Documents/Github/Gists/awesome/"
# example:
puts __FILE__
puts File.dirname(__FILE__)
puts File.expand_path(File.dirname(__FILE__))
# results: (from command line with this file)
# $ ruby how-to-get-the-directory-of-the-current-file-ruby.rb
# how-to-get-the-directory-of-the-current-file-using-ruby.rb
# .
# /Users/dev/Documents/Github/Gists/awesome/
# the following quoted from https://www.ruby-forum.com/topic/143383
#
# Phillip Gawlowski wrote:
# > On 02.01.2010 03:33, Kimball Johnson wrote:
# >> As to getting the parent directory of a file, try this:
# >>
# >> File.dirname(File.dirname(__FILE__))
# >>
# >> or for the absoluter path:
# >>
# >> File.expand_path(File.dirname(File.dirname(__FILE__)))
# >>
# >> dumb but smart?
# >
# > require "futils"
# > puts Dir.pwd
#
# Note 1: the process's current working directory is in general unrelated
# to the directory where the script itself is located.
#
# Note 2: you don't need to load any library to get access to Dir.pwd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment