Sunday, October 31, 2010

JRuby - Basics by Example



Continue with the Basics by Example; today's version of the post written in JRuby Enjoy!

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 


Greetings Program - Verbose
# JRuby basics  
require "java"  
import java.util.GregorianCalendar
import java.util.Calendar
import java.lang.System

module RbGreetProgram  
    class Greet  
        # Fields or Attributes  
        @message = ""  
        @name = ""  
        @loopMessage = 0  
        # Properties | Getters, Setters  
        def message  
          @message  
        end  
        def message=(val)  
          @message = capitalize(val)  
        end  
        def name  
          @name  
        end  
        def name=(val)  
          @name = capitalize(val)  
        end  
        def loopMessage  
          @loopMessage  
        end  
        def loopMessage=(val)  
          @loopMessage = val  
        end  
        # Constructor or Initializer Method  
        def initialize  
            @message = ""  
            @name = ""  
            @loopMessage = 0  
        end  
        # Overloaded Constructor  
        # No Overloaded Constructors/Initializers Support in Ruby  
        # Method 1  
        def capitalize(val)  
            # "if-then-else" statement  
            if val.length >= 1  
                return val.capitalize  
            else  
                return ""  
            end  
        end  
        private :capitalize  
        # Method 2  
        def salute  
            # "for" statement  
            for i in 0..@loopMessage  
                puts "#@message #@name!"  
            end  
        end  
        # Overloaded Method  
        # No Overloaded Methods Support in Ruby. New methods instead.  
         # Method 2.1  
        def salute21(message, name, loopMessage)  
            # "while" statement  
            i = 0  
            while i < loopMessage do  
                puts "#{capitalize(message)} #{capitalize(name)}!"  
                i += 1  
            end  
        end  
        # Method 2.2  
        def salute22(name)  
            # "switch/case" statement  
            dtNow = GregorianCalendar.new            
            @message = case dtNow.get(Calendar::HOUR_OF_DAY)
                when 6..11 then "good morning,"  
                when 12..17 then "good afternoon,"  
                when 18..22 then "good evening,"  
                when 23,0..5 then "good night,"  
                else "huh?"  
            end  
            puts "#{capitalize(@message)} #{capitalize(name)}!"  
        end  
    end  
  
    # Console Program  
    # Define variable object of type Greet  
    # Instantiate Greet. Call Constructor  
    g = Greet.new  
    # Call Set Properties  
    g.message = "hello"  
    g.name = "world"  
    g.loopMessage = 5  
    # Call Method 2  
    g.salute()  
    # Call Method 2.1 and Get Properties  
    g.salute21(g.message, "jRuby", g.loopMessage)  
    # Call Method 2.2  
    g.salute22("carlos")  
    # Stop and exit  
    puts "Press any key to exit..."  
    gets  
end


Greetings Program - Minimal
# JRuby basics  
require "java"  
import java.util.GregorianCalendar
import java.util.Calendar
import java.lang.System

class Greet  
    # Fields or Attributes  
    @message = ""  
    @name = ""  
    @loopMessage = 0  
    # Properties | Getters, Setters  
    def message  
      @message  
    end  
    def message=(val)  
      @message = capitalize(val)  
    end  
    def name  
      @name  
    end  
    def name=(val)  
      @name = capitalize(val)  
    end  
    def loopMessage  
      @loopMessage  
    end  
    def loopMessage=(val)  
      @loopMessage = val  
    end  
    # Constructor or Initializer Method  
    def initialize  
        @message = ""  
        @name = ""  
        @loopMessage = 0  
    end  
    # Overloaded Constructor  
    # No Overloaded Constructors/Initializers Support in Ruby  
    # Method 1  
    def capitalize(val)  
        # "if-then-else" statement  
        if val.length >= 1  
            return val.capitalize  
        else  
            return ""  
        end  
    end  
    private :capitalize  
    # Method 2  
    def salute  
        # "for" statement  
        for i in 0..@loopMessage  
            puts "#@message #@name!"  
        end  
    end  
    # Overloaded Method  
    # No Overloaded Methods Support in Ruby. New methods instead.  
    # Method 2.1  
    def salute21(message, name, loopMessage)  
        # "while" statement  
        i = 0  
        while i < loopMessage do  
            puts "#{capitalize(message)} #{capitalize(name)}!"  
            i += 1  
        end  
    end  
    # Method 2.2  
    def salute22(name)  
        # "switch/case" statement  
        dtNow = GregorianCalendar.new            
        @message = case dtNow.get(Calendar::HOUR_OF_DAY)
            when 6..11 then "good morning,"  
            when 12..17 then "good afternoon,"  
            when 18..22 then "good evening,"  
            when 23,0..5 then "good night,"  
            else "huh?"  
        end  
        puts "#{capitalize(@message)} #{capitalize(name)}!"  
    end  
end  
  
# Console Program  
# Define variable object of type Greet     
# Instantiate Greet. Call Constructor     
g = Greet.new  
# Call Set Properties     
g.message = "hello"       
g.name = "world"       
g.loopMessage = 5  
# Call Method 2       
g.salute()     
# Call Method 2.1 and Get Properties       
g.salute21(g.message, "jRuby", g.loopMessage)     
# Call Method 2.2  
g.salute22("carlos")
# Stop and exit
puts "Press any key to exit..."
gets



And the Output is:





















Where to define Class Fields/Attributes in JRuby

puts "Class Attributes Example:"  
class ClassAttributes  
    # You do not need to explicitly add the Fields/Attributes as shown below within the class:  
    # message = ""  
    # name = ""  
    # loopMessage = 0  
    # because they are added to the class as Fields/Attributes the first time they appear in  
    # your code. For example, here below, in the Initialize method,  
    # we have 2 fields (name and message)  
    def initialize  
        @message = "message" # class field  
        @name = "name"  # class field  
    end  
    # and one more within a public method (loopMessage)  
    def salute  
        @loopMessage = 1 # class field  
        localtest = 0   # local variable    
        puts "#@message, #@name, #@loopMessage"  
    end  
end  
  
# Then, you can access each of them as you normally do:  
f = ClassAttributes.new  
f.salute


Auto-Implemented Properties in JRuby
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. The following code shows how to use them just like with VB.NET, C#, C++/CLI and so on.

puts ""  
puts "Auto-Implemented Properties Example:"  
# Ruby basics  
class Greet  
    # Fields or Attributes  
    #@message = ""  
    # Manual Properties | Getters, Setters  
    #def message  
    # @message  
    #end  
    #def message=(val)  
    #  @message = capitalize(val)  
    #end  
      
    # Instead of creating a field and a manual property (as above)  
    # we use the attributes syntax to create our Auto-Implemented Property  
    # that will be linked to our @message class field/attribute  
    attr_accessor :message  
    # you can also create read or write only props using attr_writer|attr_reader  
      
    def initialize  
        @message = ""  
    end  
    def salute  
        puts "#@message"  
    end  
end  
  
g = Greet.new  
# we set the value of message through our write property  
g.message = "hello ruby"  
g.salute  
# or get the value from it as well  
puts g.message


Overloading Constructor and Methods in JRuby

Ruby does not support Overloading Methods nor Constructors, instead, you can define one method with variable arguments and code the if-elseif code to handle both(or multiple) cases yourself.

puts ""  
puts "Overloaded-like Constructor and Method Example:"  
class Overloading  
    # Constructor with variable arguments  
    def initialize(*args)  
        # if args list/sequence is not empty we use the arguments,  
        # otherwise we use the class fields  
        if args.size > 0  
            @message = args[0]  
            @name = args[1]  
            @loopMessage = args[2]  
        else  
            @message = 'empty_message'  
            @name = 'empty_name'  
            @loopMessage = 2  
        end  
    end  
    # Method  with variable arguments  
    def salute(*args)  
        # if args list/sequence is not empty we use the arguments,  
        # otherwise we use the class fields  
        if args.size > 0  
            for i in 1..args[2]  
                puts "#{args[0]}, #{args[1]}!"  
            end  
        else  
            for i in 1..@loopMessage  
                puts "#@message, #@name!"  
            end  
        end  
    end  
end  
  
# and now we use the "overloaded-like" constructor and method  
# calling constructor without parameters  
o1 = Overloading.new  
# calling method without parameters  
o1.salute  
# calling method with parameters  
o1.salute("Hello", "JRuby", 3)  
# calling constructor with with parameters  
o2 = Overloading.new("Hello", "Carlos", 2)  
# calling method without parameters  
o2.salute



And the Output is:




No comments:

Post a Comment