Ruby and class constants

I have a confusion to access class constants, for example:

class GoogleApi
  API_ENDPOINT = 'https://www.google.com/'
end

I can’t understand what’s the difference between GoogleApi.API_ENDPOINT and GoogleApi::API_ENDPOINT?

Furthermore why sometimes when I try to access the constant using a GoogleApi.API_ENDPOINT and it raises a NoMethodError: undefined method error?

Thanks,
Lucio

:: is used to access the constant - the GoogleApi classname is the ‘namespace’ for the constant.

. is used to access a class method (so will not work with your API_ENDPOINT)

class A
  B = 3

  def self.C
    4
  end
end

> A::B  # gets the constant value
3
> A.C  # calls the method named C
4

You get an error with either A.B, as B is not a method, or A::C, as C is not a constant.

(The same works with ‘module’ in place of ‘class’.)

2 Likes

thanks for the answer, I also had this problem

This applies to the precise task, described by luciotbc, in the OP, above.

However, you must understand that the point ‘.’ is referring quite generally to an object, the two colons ‘::’ to a class.

Example

puts "file size is " << File::size(‘/tmp’).to_s
puts "file size is " << File.new(‘/tmp’).size.to_s

produce identical output, while two different methods are employed. The File-class has 1 class-method size() which belongs to an object of class ‘Class’ of the name of File. The File class has also 1 Instance-method size() belonging to each object of class ‘File’.
You can write the second line as

fl = File.new(‘/tmp’)
puts "file size is " << fl.size.to_s

As File::size() is obviously a call to a class-method, you can also write it as File.size and have identical output (where File is an object of type class). The double-colon is though clearer.