Open Source Development on the IBM i: Getting Started with Ruby

Linux / Open Source
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Pete Helgren lays out the basics of Ruby, a popular open source programming language for building IBM i applications

by Pete Helgren

Editor's note: This article is excerpted from chapter 6 of Open Source Starter Guide for IBM i Developers.

Most of the Ruby language constructs follow a predictable pattern that we, as programmers, are familiar with. It is the implementation of those constructs that can make the "getting started" step a bumpy ride. So, let's get on the horse and ride!

Variables

Unlike RPG and more like JavaScript (if you are familiar with it), Ruby is a dynamically typed language. That is, you don’t have to declare a type when you declare a variable.

You could assign a variable this way:

the_meaning_of_life = 42

If you do, Ruby will see the variable as a number (Fixnum class, actually). Later, you could assign the same variable to a different type:

the_meaning_of_life = 'Money, fame and fortune'

Ruby won't even blink. If you happened to capitalize the first character of the variable, Ruby will define it as a constant. And, although you can change the value of a constant, Ruby will complain about it with a warning about the change.

bash-4.2$ irb

irb(main):001:0> the_meaning_of_life = 42

=> 42

irb(main):002:0> the_meaning_of_life = 'Money, fame and fortune'

=> "Money, fame and fortune"

## Note no complaint about the change.....

irb(main):003:0> The_meaning_of_life = 42

=> 42

irb(main):004:0> The_meaning_of_life = 'Money, fame and fortune'

(irb):4: warning: already initialized constant The_meaning_of_life

(irb):3: warning: previous definition of The_meaning_of_life was here

=> "Money, fame and fortune"

Scope

We also have variables that can be of local, global, class, or instance scope.

Local scope is pretty much what you would expect, and global variables are pretty much the same in Ruby as in other languages. Each variable will have a scope that it is declared in based on its location in the code.

You probably have not come across class and instance variables either because, well, RPG isn't object-oriented, so the concept of classes and instances of classes are not part of your nomenclature in RPG. Very quickly, in most cases a class represents a template or a "mold" of what an object should look like from the standpoint of the design of variables and function. It's a prototype of what the object would look like if you created one. So, a class variable would be a variable that would hold a value across instances of that class. This could come in handy if you are creating many instances of a class and want an aggregate count or total across all instances of that class. An instance variable would be, ahem, a variable that is unique to only that instance of the class. No mystery. But the declaration of each of the variables has some convention to it:

  • Local variables: start with a lowercase letter or an underscore "_".
  • Global variables: start with a $ sign.
  • Class variables: start with a double "at" sign: @@
  • Instance variables: start with a single "at" sign: @

The best way to demonstrate how each of these work is to demonstrate them (!).

### Start with a global that will persist for the session

$aGlobalVariable = 5

## Then create a class to demonstrate class and instance differences

class Demo

## class Variable

@@classVariable = 0

      ## We need to initialize the variable or else it will be nil when we

      ## add it to itself in the add_me method. Initialization will happen when we

      ## invoke "New" on the class to create the instance  

      def initialize()

            @instanceVariable = 0

      end

      ## a simple function to output these variables

      def add_me()

            @@classVariable += 1 # increment the class variable

            @instanceVariable += 1 # increment the instance variable

            output_class_var()

            puts "Global total is now #$aGlobalVariable"

            puts "My instance variable is now #@instanceVariable"

            puts " "

      end

      def add_me_twice()

            ## Run this guy to see what happens to a global variable

            $aGlobalVariable+=1

            add_me

      end

      def output_class_var

            puts "Class total is now #@@classVariable"

      end

end

# Create the class instances (objects), which will initialize the instance variable

i1 = Demo.new

i2 = Demo.new

# invoke the methods

i1.add_me()

i2.add_me()

i2.add_me_twice()

i3 = Demo.new

i3.output_class_var()

The output will be this:

Class total is now 1

Global total is now 5

My instance variable is now 1

Class total is now 2

Global total is now 5

My instance variable is now 1

Class total is now 3

Global total is now 6

My instance variable is now 2

Class total is now 3

The first invocation is predictable. Those values were set in the instance. But in the next invocation of add_me in a different instance of the class, we see the magic start to happen. Even though i2 knows nothing about i1 and what it is doing, it is affected by the method that updates the global variable. And if we create a new object instance after the class variable has been updated, we get the new total along with it, as you can see when i3 invokes the output_class_var method.

Trying to keep track of the variables and their scope can be a challenge, but what I like here is that we can use the underscore (_), dollar sign ($), at sign (@), and double at signs (@@) as part of the variable name to help us keep track of what is what. Normally, I would have to resort to using special naming conventions to remind me of the scope. This way, I can know exactly what the scope is by the name used.

Built-in Functions

At the simplest level, there are math functions:

irb(main):005:0> 1+1

=> 2

Fortunately, it can also do math correctly: 1 + 1 is 2.

Ruby math follows the correct order of precedence rule rather than the "calculator" (sequence) rules.

irb(main):006:0> 20-10*10

=> -80

Multiplication has a higher order of precedence than subtraction. And you can "force" calculations into a higher precedence by using parentheses:

irb(main):007:0> (20-10)*10

=> 100

Beyond the "primitive" math functions of add, subtract, multiply, and divide are a whole host of math functions found in the Math module, such as square root (sqrt).

irb(main):008:0> Math.sqrt(25)

=> 5.0

Or you could just include the Math module and then execute the functions directly:

irb(main):009:0> include Math

=> Object

irb(main):010:0> sqrt(25)

=> 5.0

OK. We have seen a couple of things here. We've seen the native arithmetic functions and those contributed by the Math modules (we'll be jumping into modules and classes shortly). We still have a few more commonly used features of the Ruby language that are worth exploring.

Containers

Back to the workbench that contained many items, including my underwear.

Arrays and hashes are typical containers. The RPG language has arrays, but hashes are a bit different. Let’s start with arrays. You can define them with literals using brackets ([]) or by declaring an object type: Array.

The elements do not have to all be the same type. You can mix and match:

irb(main):011:0> a = [123,'cat','bird',6,'dog']

=> [123, "cat", "bird", 6, "dog"]

irb(main):012:0> puts a[3]

6

So we have an array of four items, strings, and numbers and have assigned them to the variable a. From that context, we know we have an array type. Let's check that:

irb(main):013:0> a.class

=> Array

It confirms what we already know.

We can also create a new array object:

irb(main):014:0> b = Array.new()

=> []

You can assign values:

irb(main):015:0> b[0]=123

=> 123

irb(main):016:0> b[1]='cat'

=> "cat"

irb(main):017:0> b[2]='bird'

=> "bird"

irb(main):018:0> b[3]=6

=> 6

irb(main):019:0> b[4]='dog'

=> "dog"

And you can output those arrays. More importantly, you can iterate through them, which is what you commonly do with arrays. Here is an example of iterating through an array:

irb(main):020:0> b.each{|i| puts i}

123

cat

bird

6

dog

=> [123, "cat", "bird", 6, "dog"]

What might blow your mind a bit is the {|i| puts i} part. I know it did for me the first time I saw the syntax. What you are seeing is a "block," which is a way of defining an anonymous function or closure. In RPG, we generally define each of the functions we"ll call in the RPG program. In Ruby (and not just Ruby, but several other languages, such as JavaScript and Python), you can execute a function without naming it. So, in the example above, b, an array, has an each method that, when invoked, iterates through the array passing "each" element. Passing "each" to what? Passing to a block function, in this case. The function takes a parameter (| |), and then the rest of the function block defines what to do with that parameter puts i. A single-line function is easily represented with the { | | } syntax. But if you have a complex block, you can use the do ... end syntax, which basically defines what to "do" between do and end.

On the face of it, it's pretty simple, but you don't often see a simple block like this. Very often, blocks are passed to methods, and then things get a little more wiggy.

Take a look at something like this:

def say_stuff

yield ("Pete", "ruby")

end

say_stuff do |name, lang|

puts "#{name} loves to program #{lang}"

end

We have a method called say_stuff, which takes no parameters and has a yield method that is passing two parameters.

Below that, we have a call to the say_stuff method, which is passing a block. So what is going on here? Le's start with yield. Yield basically says, "Stop here and call whatever was passed in as a block." Frankly, at this point, the POLA (Principle of Least Astonishment) is completely broken IMHO because my head exploded the first time I tried to puzzle out the code. Ruby allows a block to be passed to any method, even if it isn't used. But, if there is a yield, then you have to pass it a block or it will raise an exception. (Well, almost. You can use the block_given? method to test to see whether a block was passed and then act accordingly.)

The other thing that strikes me as bass-ackwards in this approach is that most of the magic is in the block that is called rather than the method. So, things take a while to sink in. And here is the result:

bash-4.2$ ruby block_stuff.rb

Pete loves to program ruby

So, we invoke the say_stuff method, passing in our block (the stuff between the do and end). We run line number 2, which yields to the block passed in, passing in the two parameters that the block uses. The function in the block runs, and then the function returns, and then the method returns. Done.

You see plenty of this in Ruby, so get used to it. The Internet has many examples of blocks and methods. This example barely scrapes the surface. But my goal is to get you familiar with the language and expose you to Ruby stuff so your head stays intact, not teach you everything you need to know.

Hashes

Our little trip down the array path got us diverted on to blocks. But blocks are used extensively with arrays because normally you are iterating through the array to do something with each value in the array or at least examine each value. Hashes are similar to arrays. There really isn't an equivalent data type in RPG that I can think of (a data structure, maybe). But, in principle, hashes are arrays of name-value or key-value pairs, and sometimes key:value or name:value. And the advantage to the hash design is that basically anything can be the key, so it becomes a great way to store stuff with arbitrary keys and values. In an array, your values are stored in sequential buckets. In a hash, they could be stored anywhere; you have to find it by key. That is also a disadvantage of hashes: they have no order like an array would have, so finding the value by key can be slow.

But a key-value pair is highly flexible. In fact, when we look at Rails and a few other Web technologies later on, the key-value pair will raise its head in the form of JSON. So, this isn't just an intellectual exercise; there is some goodness here!

To create a hash, you can do it two ways (just like arrays). You can use literals or use Object.new to create a "new" object of "type." Option #1 will let us use symbols and "rocket" nomenclature to assign key-value pairs:

h = {'cat'=>'unlikeable','dog'=>'best friend','horse'=>'giddy up','pig'=>'squeal!'}

And as a side note, you can use symbols for keys as well:

h = {:cat=>'unfriendly',:dog=>'best friend',:horse=>'giddy up',:pig=>'squeal'}

Option 2 is to invoke the new method on a hash object:

creatures = Hash.new

And then assign the key-value pairs:

creatures['cat']='unlikeable'

creatures['dog']='best friend'

creatures['horse']='giddy up'

creatures['pig']='squeal!'

How to access the values? Refer to the key, and the value will be returned. This is how to iterate though the hashes:

creatures = Hash.new

creatures['cat']='unlikeable'

creatures['dog']='best friend'

creatures['horse']='giddy up'

creatures['pig']='squeal!'

creatures.each {|creature,appeal| puts "#{creature} is #{appeal}" }

The result of the above code would be this:

cat is unlikeable

dog is best friend

horse is giddy up

pig is squeal!

Really it just comes down to referencing the key to return the value:

puts creatures['cat'] would output "unlikeable".

When it comes to hashes, if you can keep the concept of key-value pair in your head, you'll do fine. With simple syntax, working with hashes is a breeze, and in Ruby (and Rails in particular), you'll use a lot of them.

BLOG COMMENTS POWERED BY DISQUS