Defining Class Constants in JRuby
In this example you will learn about using Class Constants in JRuby program. Constants can be defined within the scope of classes, but they are not as instance variables, constants can be accessed from outside the class. Constants have name starting with the upper case letter.
In this example we have created a class and this class consists of three class constants Constant1, Constant2, Constant3 and we have initialized them with integer values 10, 20, 30 respectively. printAll method of class ConstantClass will print all constants values since they are accessible within class.
"puts Constant1" outside the class will report an error because it can be accessed outside the class with the class name as given below:
"ConstantClass::Constant1" |
Here is the example code of ConstantsJRuby.rb as follows:
ConstantsJRuby.rb
# Class constants Example class ConstantClass Constant1 = 10 Constant2 = 20 Constant3 = 30 def printAll puts "Value of first constant = #{Constant1}" puts "Value of first constant = #{Constant2}" puts "Value of first constant = #{Constant3}" end end const = ConstantClass.new puts const.printAll # puts Constant1 will invoke NameError # uninitialized constant Constant1 puts "Constant Value ==> #{ConstantClass::Constant1}" puts "Constant Value ==> #{ConstantClass::Constant2}" puts "Constant Value ==> #{ConstantClass::Constant3}" |
Output:
After executing ConstantsJRuby.rb on command prompt with jruby command, you will get the following output:
C:\JRuby>jruby ConstantsJRuby.rb Value of first constant = 10 Value of first constant = 20 Value of first constant = 30 nil Constant Value ==> 10 Constant Value ==> 20 Constant Value ==> 30 |