23
Sat, Nov
1 New Articles

Open Source Starter Guide for IBM i Developers: Language Basics

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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!

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:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 1

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:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 2

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.

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 3

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 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 (!).

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 4

The output will be this:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 5

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:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 6

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.

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 7

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

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 8

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).

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 9

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

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 10

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:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 11

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:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 12

It confirms what we already know.

We can also create a new array object:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 13

You can assign values:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 14

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:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 15

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:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 16

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:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 17

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:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 18

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

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 19

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

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 20

And then assign the key-value pairs:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 21

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

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 22

The result of the above code would be this:

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 23

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

Open Source Starter Guide for IBM i Developers: Language Basics - Figure 24

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.

Next time: Program Structure in Ruby. Want to learn more?  You can pick up Peter Helgren's book, Open Source Starter Guide for IBM i Developers at the MC Press Bookstore Today! 

Peter Helgren

Peter Helgren is programmer/team lead at Bible Study Fellowship International. Pete is an experienced programmer in the ILE RPG, PHP, Java, Ruby/Rails, C++, and C# languages with more than 25 years of system 3X/AS400/iSeries/IBM i experience. He holds certifications as a GIAC certified Secure Software Programmer-Java and as an MCSE. He is currently executive vice president on the COMMON Board of Directors and is active on several COMMON committees. His passion has always been in system integration, and he focuses on open-source applications and integration activities on IBM i. Pete is a speaker/trainer in RPG modernization, open-source integration, mobile application development, Java programming, and PHP and actively blogs at petesworkshop.com.


MC Press books written by Peter Helgren available now on the MC Press Bookstore.

Open Source Starter Guide for IBM i Developers Open Source Starter Guide for IBM i Developers
Check out this practical introduction to open-source development options, including XMLSERVICE, Ruby/Rails, PHP, Python, Node.js, and Apache Tomcat.
List Price $59.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: