Home Tutorials Jruby Defining Class Constants in JRuby
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Defining Class Constants in JRuby

Advertisement
In this example you will learn about using Class Constants in JRuby program.

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

Download Source Code

     

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 30, 2008

Ask Questions?    Discuss: Defining Class Constants in JRuby  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com