I am new to Ruby (coming from java background) and I was wondering whats the behavior for constants in RoR applications and in general Ruby.
Are they just initialized once, like java static variables?
I am initializing a fairly big array of hash as a constant, so I want to be sure if I am doing it right?
Thanks for your help.
module MyModule
MY_CONST = [{...}开发者_运维百科, {...}, {...}, {...}, {...}, ...]
Not actually. From the Variables and Constants section of the Programming Ruby guide:
...
A Ruby constant is also a reference to an object. Constants are created when they are first assigned to (normally in a class or module definition). Ruby, unlike less flexible languages, lets you alter the value of a constant, although this will generate a warning message.
MY_CONST = 1
MY_CONST = 2 # generates a warning
produces:
prog.rb:2: warning: already initialized constant MY_CONST
精彩评论