Ruby/Language Basics/Constants
Материал из Wiki.crossplatform.ru
Array constant
RGB_COLORS = [:red, :green, :blue] # => [:red, :green, :blue] RGB_COLORS << :purple # => [:red, :green, :blue, :purple] RGB_COLORS = [:red, :green, :blue] # warning: already initialized constant RGB_GOLORS RGB_COLORS # => [:red, :green, :blue] RGB_COLORS.freeze RGB_COLORS << :purple # TypeError: can"t modify frozen array
Change the value of Pi, it"ll let you do it, but you"ll get a warning:
Pi = 3.141592 Pi = 500
Constants are defined within the scope of the current class and are made available to all child classes, unless they"re overridden:
Pi = 3.141592 class OtherPlanet Pi = 4.5 def OtherPlanet.circumference_of_circle(radius) radius * 2 * Pi end end puts OtherPlanet.circumference_of_circle(10) puts OtherPlanet::Pi puts Pi
Constants in Ruby start with an uppercase letter
IP_SERVER_SOURCE = "111.111.333.055" print IP_SERVER_SOURCE
freeze does nothing since Fixnums are already immutable.
HOURS_PER_DAY = 24 HOURS_PER_DAY.freeze # This does nothing since Fixnums are already immutable. HOURS_PER_DAY = 26 # warning: already initialized constant HOURS_PER_DAY HOURS_PER_DAY # => 26
Ruby allows you to change the values in constants by assigning a new value to them:
CONST = 1
CONST = 2
print CONST
The Scope of Constants
def circumference_of_circle(radius) 2 * Pi * radius end Pi = 3.141592 puts circumference_of_circle(10)