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’.)

1 Like

thanks for the answer, I also had this problem

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs