Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a file in ruby - differences

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.

like image 923
Siva Gnanam Avatar asked Feb 26 '14 08:02

Siva Gnanam


People also ask

How do I read data from a file in 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.

What are the ruby file open modes?

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.

What is file handling in Ruby?

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.


2 Answers

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)

like image 51
avl Avatar answered Sep 24 '22 14:09

avl


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.

like image 31
Arup Rakshit Avatar answered Sep 24 '22 14:09

Arup Rakshit