__FILE__ in Ruby

What is __FILE__ in Ruby?

You must have come across the mysterious term __FILE__ while reading Ruby code. It's a magic variable that returns the name of the current file. This short post shows a few different use cases that I found while reading the Rails source code.

1 min read

While reading open source Ruby code, I often come across this mysterious looking __FILE__ variable (among others) that I never bothered to look into. After coming across it umpteenth time this evening, I decided to read up on it and here's everything I learned.

__FILE__ is a magic variable that contains the filename with extension of the current file that's being executed. For example, if you're running code in a file named main.rb, __FILE__ will return "main.rb".

# scratch/main.rb

puts __FILE__  # main.rb

You can use __FILE__ with File.expand_path to get the absolute path of the current file.

puts File.expand_path __FILE__

# ~/Software/rails/learn/scratch/main.rb

Here're some interesting use cases I found for this variable while browsing the Rails source code.

  • Get the name of the current directory
# actionmailbox/lib/action_mailbox/mail_ext.rb

  • To set the text for error messages in class_eval or module_eval functions, which evaluate the given string or block in the context of the module.
class_eval <<-RUBY, __FILE__, __LINE__ + 1
  def #{sym}(...)
    custom(Mime[:#{sym}], ...)

module_eval <<-CODE, __FILE__, __LINE__ + 1
  def #{option_name}
  def #{option_name}=(value)
    options[:#{option_name}] = value

Note: As you might have guessed, the __LINE__ variable returns the current line number.

That's it. I hope you found this short post helpful and you learned something new.

As always, if you have any questions or feedback, didn't understand something, or found a mistake, please leave a comment below or send me an email. I reply to all emails I get from developers, and I look forward to hearing from you.

If you'd like to receive future articles directly in your email, please subscribe to my blog. If you're already a subscriber, thank you.