File access in ruby ​​- differences

What is the difference between the following statements?

#(not working)
File.exists?("path to file")

#(working)
::File.exists?("path to file")

I used the above statements as part of Chef Ruby.

+3
source share
3 answers

Here you can try to reproduce your problem:

Does not work:

class Foo< BasicObject
  def self.file_size
     File.size(__FILE__)
  end
end

p Foo.file_size # uninitialized constant Foo::File (NameError)

The reason is the class Filethat is accessible at the top level (i.e. in the class area Object) and inside any class that is a direct / indirect subclass Object. But Fooit has nothing to do with it Object; you won’t be able to access it inside Foounless you tell it where the Fileclass (or constant) is actually available from.

Job:

class Foo< BasicObject
  def self.file_size
     ::File.size(__FILE__)
  end
end

p Foo.file_size # => 132

Foo Object, ( :: ) Ruby, File ( class (s) Ruby) Foo. , Ruby.

, .

+5

, File.exists?("path to file"), File. ::, ruby, File Object (Object::File)

+6

, File.exists? - File.exist?

, :

", ?" "Object.exist?"

- , " " , , ruby .

:: - .

, , .

-1
source

All Articles