Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Ruby constant mean?

Tags:

ruby

constants

What does Ruby constants really mean? The following code doesn't show any 'constant' attribute. The warning is there, but I still get to change what A refers to.

A = 1
puts A # => 1
A = 2  # warning: already initialized constant A
puts A # => 2

Or is Ruby constants are just an indication without any enforcement?

like image 471
bryantsai Avatar asked Dec 30 '09 00:12

bryantsai


1 Answers

That's right, constants are just like variables in ruby, but you get a warning if you change them.

Also, there's one difference with mere variables: You can access constants even if they are defined inside another class or module, for example given this snippet:

module Constants
  PI = 3,1415
  other = "variable"
end

You can reach PI doing Constants::PI while Constants::other will not work.

like image 73
Pablo Fernandez Avatar answered Oct 29 '22 06:10

Pablo Fernandez