It seems the __FILE__
and __LINE__
constants are dynamically updated with the current file and line numbers under execution, I am wondering how is the behaviour implemented in Ruby?
I've greped the source code but there are too many noises for __LINE__
and __FILE__
appearance, I am wonder anyone could help me point to the source code and provide a clue to understand its behaviour.
Explanation in either Rubinis
or MRI
will be fine.
The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.
A File is an abstraction of any file object accessible by the program and is closely associated with class IO . File includes the methods of module FileTest as class methods, allowing you to write (for example) File. exist?("foo") .
Both __FILE__
and __LINE__
get replaced by literals directly in the parser:
case keyword__FILE__:
return NEW_STR(rb_external_str_new_with_enc(ruby_sourcefile, strlen(ruby_sourcefile),
rb_filesystem_encoding()));
case keyword__LINE__:
return NEW_LIT(INT2FIX(tokline));
In other words, they behave exactly as if you had typed in the resulting string or number yourself.
Note that for __LINE__
, this doesn't always behave how you'd expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With