I don’t plan to spend a lot of time in the minutiae of the Ruby language. The goal of this series is to give you enough to go on to get started.
Editor's Note: This article is excerpted from chapter 6 of Open Source Starter Guide for IBM i Developers, by Pete Helgren.
And although Ruby is based on POLA, there is enough “surprise!” in the way things work that it is worthwhile to go over some of the basic things and at least point out where I got either derailed or stumped. Sometimes, Grasshopper, all you need is a little enlightenment!
You could assign a variable this way:
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:
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.
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 concepts of classes and instances of classes are not part of your nomenclature in RPG. From chapter 5, you should have a rough idea of what a class and an instance of a class would be. 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 works is to demonstrate them (!).
The output will be this:
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.
At the simplest level, there are math functions:
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.
Multiplication has a higher order of precedence than subtraction. And you can “force” calculations into a higher precedence by using parentheses:
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).
Or you could just include the Math module and then execute the functions directly:
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.
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:
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:
It confirms what we already know.
We can also create a new array object:
You can assign values:
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:
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:
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? Let’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:
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.
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:
And as a side note, you can use symbols for keys as well:
Option 2 is to invoke the new method on a hash object:
And then assign the key-value pairs:
How to access the values? Refer to the key, and the value will be returned. This is how to iterate though the hashes:
The result of the above code would be this:
Really it just comes down to referencing the key to return the value:
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.