What is the different between the following statements?
#(not working)
File.exists?("path to file")
#(working)
::File.exists?("path to file")
I used above statements in Chef framework of Ruby.
Opening a File in Ruby There are two methods which are widely used − the sysread(n) and the read() method. The open method is used to open the file, while the sysread(n) is used to read the first "n" characters from a file, and the read() method is used to read the entire file content.
Ruby allows the following open modes: "r" Read-only, starts at beginning of file (default mode). "r+" Read-write, starts at beginning of file. "w" Write-only, truncates existing file to zero length or creates a new file for writing.
It is a way of processing a file such as creating a new file, reading content in a file, writing content to a file, appending content to a file, renaming the file and deleting the file. Common modes for File Handling. “r” : Read-only mode for a file. “r+” : Read-Write mode for a file.
There is another constant named File
in the scope where you are using File.exists?("path to file")
. But when you use the ::
operator, you are telling ruby to find the File
constant in Object
(Object::File
)
Here is possible try to replicate your issue :
Not working :
class Foo< BasicObject
def self.file_size
File.size(__FILE__)
end
end
p Foo.file_size # uninitialized constant Foo::File (NameError)
The reason is File
class is available to the top level ( i.e. in the scope of the class Object
) and inside any class which is a direct/ indirect subclass of Object
. But Foo
has no relation with Object
, you wouldn't be able to access it inside Foo
, if you don't tell it, from where File
class ( or constant ) actually accessible.
Working :
class Foo< BasicObject
def self.file_size
::File.size(__FILE__)
end
end
p Foo.file_size # => 132
Although here also, Foo
has no relation with Object
, but we are explicitly ( by using ::
constant scope resolution operator ) telling Ruby that from where we are trying to access the File
class ( Remember class(s) are also constant in Ruby) inside Foo
class. Thus here is no objection from Ruby.
Check out if such situation is present in your code too.
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