# What is __FILE__ in Ruby?

*Published on February 03, 2024*

---


While reading open source&nbsp;Ruby code, I often come across this mysterious looking` __FILE__`&nbsp;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__`**&nbsp;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&nbsp;`main.rb`,&nbsp;`__FILE__`&nbsp;will return&nbsp;`"main.rb"`.

```ruby
# scratch/main.rb

puts __FILE__  # main.rb
```

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

```ruby
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

```ruby
# actionmailbox/lib/action_mailbox/mail_ext.rb

File.expand_path(File.dirname(__FILE__))
```

- To set the text for error messages in&nbsp;`class_eval`&nbsp;or&nbsp;`module_eval`&nbsp;functions, which evaluate the given string or block in the context of the module.

```ruby
class_eval <<-RUBY, __FILE__, __LINE__ + 1
  def #{sym}(...)
    custom(Mime[:#{sym}], ...)
  end
RUBY

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

_**Note:**_&nbsp;_As you might have guessed, the_&nbsp;_`__LINE__`_&nbsp;_variable returns the current line number._

