开发者

Ruby/Rails constant behavior

开发者 https://www.devze.com 2023-01-16 02:17 出处:网络
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.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消