Search code examples
rubyseparatorpseudo-globals

How to override `File::SEPARATOR`


Documents for File.join states that:

join(string, ...)string

Returns a new string formed by joining the strings using File::SEPARATOR.

File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"

However, the result below shows a different behavior.

File::SEPARATOR #=> "/"
File::SEPARATOR = "doge"
File::SEPARATOR #=> "doge"
File.join("so", "wow") #=> "so/wow"

Could anybody explain what is happening? Is there a way to override this behavior by setting File::SEPARATOR to another value?

I don't have a specific use case for this, nor am I looking for workarounds.. just curious. Thank you in advance.


Solution

  • When you define redefine the constant, all future Ruby code will see this new value.

    However the implementation of File.join is in C which references the C constant of the separator which you have not redefined.

    Any C code will reference the original value (that was set when the Ruby interpreter was initialized) whereas any Ruby code will reference the overridden/redefined value.