26
Fri, Apr
1 New Articles

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

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.

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

$0.00 Raised:
$

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: