File Methods: Part One
Many of us are familiar with how to move around different directories or files when we're using our favorite editors. Our Ruby programs, or gems we use, often need to do similar movements to different directories, or to load different files. How can Ruby programs know which directories a certain file is in, or load other files? __FILE__ For starters, __FILE__ is a Ruby constant which gives us a String represenation of the path to the current file, from where it was called. For instance, if we have a file example.rb which looks like this: puts __FILE__
and I run it, I'll get $ ruby example.rb
example.rb
If we move one directory up though, so that example.rb is now in ruby_weekly/example.rb , and run it, we'll see the path including the ruby_weekly directory: $ ruby ruby_weekly/example.rb
ruby_weekly/example.rb
What if we need the full filepath of a file on a machine, not just the one we're running from? File.expand_path File.expand_path will give us the full filepath. For instance, if we change example.rb to look like this:
puts File.expand_path(__FILE__)
and run it, we'll see $ ruby ruby_weekly/example.rb
/Users/jemmaissroff/ruby_weekly/example.rb
This week's tip is laying the groundwork for us to dig into File.join and File.dirname (including a new Ruby 3.1 arg) next week! |