• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • Knee-Deep In Ruby Waters

    January 27, 2015 Aaron Bartell

    In Testing The Ruby Waters I introduced you to Ruby and how to use irb (interactive Ruby shell) to easily run and test Ruby code. In this article I expound on that and introduce more features of the Ruby programming language as it relates to an IBM i programmer. In particular, Ruby methods and one form of encapsulation.

    Ruby is an object-oriented language; everything in Ruby is an object. But that doesn’t inhibit Ruby from being used in a more procedural approach. Below is a Ruby program named “say_hi.rb” with a method definition of “hi”, and then the invocation of “hi”. Note, Ruby methods are like subprocedures in RPG. Notice how there isn’t any sort of a class definition or any other means of encapsulating around the “hi” method. Ruby does have the ability to define a class, but it isn’t required, and that’s a good thing.

    --- say_hi.rb ---
    def hi name
     puts "hi #{name}"
    end
     
    hi "Aaron"
    -------
    

    To invoke a Ruby program you need to pass the .rb file to the ruby runtime, as follows. Note I am in the same directory as the program in this case. If you are in a different directory you need to adequately convey the file path: full or relative. Also note I am in a shell environment, which you can learn more about here.

    Let’s mix things up a bit and copy/paste this test program into irb, as shown below. Note how I changed the order by first having the method invocation and then the method definition. (Learn more about irb here.)

    Here we learn an interesting aspect of Ruby in that when hi was called there wasn’t yet a method definition so it threw an error. Before a method can be called upon it must first be defined. This is where we can start encapsulating our code by storing the hi method definition in a separate file, as shown below. Encapsulating (a.k.a., modularizing) is a familiar concept to RPG’ers by way of *SRVPGMs and the like.

    Below we see the hi method definition now exists in file talk.rb. Then the say_hi.rb file needs to have a require_relative statement to bring the talk.rb file into say_hi.rb. Think of require_relative as being similar to a /copy statement in RPG. Note, talk.rb and say_hi.rb are located in the same directory.

    --- talk.rb ---
    def hi name
     puts "hi #{name}"
    end
    -------
    
    --- say_hi.rb ---
    require_relative 'talk'
     
    hi "Aaron"
    -------
    

    Now when we invoke say_hi.rb again we get the expected results of “hi Aaron” in the terminal. To take this example further it would be good to wrap the hi method in a namespace so it doesn’t conflict with any other methods named hi. To do this we can use Ruby’s module concept, which is similar in nature to Java’s package concept. RPG doesn’t yet have namespaces so what I usually do is prefix the subprocedure with the name of the module (i.e., Cust_getAddress).

    Below I’ve added a module statement named Talk that wraps the hi method definition. I also need to declare that the hi method belongs to the Talk module so we name it self.hi instead. Why do we need to add “self.”? That’s a bigger conversation for another day, but it has to do with what’s called “mixins”.

    --- talk.rb ---
    module Talk
      def self.hi name
       puts "hi #{name}"
      end
    end
    -------
    

    Then in say_hi.rb we need to qualify the call to be Talk.hi. Tada! We now have namespaced methods and modularized code!

    --- say_hi.rb ---
    require_relative 'talk'
     
    Talk.hi "Aaron"
    -------
    

    Next let’s learn whether Ruby is passing parameters by value or reference. RPG can do both by using or omitting the VALUE keyword on a subprocedure definition. The prevailing user community documentation says Ruby is strictly pass-by-value, but this isn’t entirely correct. The normal approach to proving that Ruby is pass-by-value is to first assign a variable a value, call a method that changes the passed-in variable, and then display the original variable value again from the caller, as shown below.

    --- talk.rb ---
    module Talk
      def self.hi name
        name = "#{name}, welcome to the jungle."
        puts "callee: #{name}"
      end
    end
    -------
    
    --- say_hi.rb ---
    require_relative 'talk'
     
    x = "Aaron"
    Talk.hi x
    puts "caller after call: #{x}"
    -------
    

    Now when we invoke the program again we will see the value of variable x remains the same even after the hi method changes the value of the name variable. This is where most usually say “Ha! See, obviously Ruby is pass-by-value.”

    What actually happens is a Ruby method call passes an object ID reference, and if the variable is modified in the method then, and only then, it will create a new object ID reference for that variable so the caller’s variable value isn’t altered. This is called copy-on-write and is an optimization strategy where two or more variables can point at the same object reference until one of them needs to change.

    Let’s prove the copy-on-write concept by displaying the object id for each variable at various stages throughout the method call to see when it changes.

    --- talk.rb ---
    module Talk
      def self.hi name
        puts "n1:#{name.object_id}"
        name = "#{name}, welcome to the jungle."
        puts "n2:#{name.object_id}"
      end
    end
    -------
    
    --- say_hi.rb ---
    require_relative 'talk'
     
    x = "Aaron"
    puts "x1:#{x.object_id}"
    Talk.hi x
    puts "x2:#{x.object_id}"
    -------
    

    Below are the results and we can see that as soon as the Talk.hi method altered the name variable it produced a new object ID, and when control was returned to the caller that x still had the original object ID.

    From this little exercise we now know that Ruby is technically pass-by-reference, but because of its copy-on-write approach it feels like pass-by-value. While this is definitely beyond a beginner’s topic, I thought the distinction was important given we have both approaches in RPG, though not a copy-on-write approach. Stay tuned for more on the Ruby language in future articles.

    Aaron Bartell is Director of IBM i Innovation for Krengel Technology, Inc. Aaron facilitates adoption of open source technologies on IBM i through professional services, staff training, speaking engagements, and the authoring of best practices within industry publications and www.litmis.com. With a strong background in RPG application development, Aaron covers topics that enable IBM i shops to embrace today’s leading technologies including Ruby on Rails, Node.js, Git for RPG source change management and RSpec for unit testing RPG. Aaron is a passionate advocate of vibrant technology communities and the corresponding benefits available for today’s modern application developers. Connect with Aaron via email at abartell@krengeltech.com. Aaron lives with his wife and five children in Southern Minnesota. He enjoys the vast amounts of laughter having a young family brings, along with camping and music. He believes there’s no greater purpose than to give of our life and time to help others.

    RELATED STORIES

    Testing The Ruby Waters

    Bash Is Not A Shell Game

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags:

    Sponsored by
    Raz-Lee Security

    With COVID-19 wreaking havoc, cybercriminals are taking advantage of the global impact that it has had on our families, our businesses and our societies. It is more important now than ever to ensure that IT systems are protected, so that when all of this is behind us, we can get back to business as usual as quickly as possible.

    iSecurity Anti-Ransomware protects organizations against ransomware attacks and other kinds of malware that may access and change business-critical data on your IBM i. It even protects against zero-day attacks. Anti-Viruses can only report on the damage an attack has caused, but not stop it.

    iSecurity Anti-Ransomware has been recently enhanced with a Self-Test feature that allows you to simulate a ransomware attack on your IBM i. The simulated attack is limited to the test folder and cannot harm any other folders or files. This new feature lets organizations see how they are protected against known or unknown ransomware.

    Key Features:

    • Real-time scanning for known and unknown ransomware threats.
    • Blocks and disconnects the intruder.
    • Instantaneously sends alerts to SIEM as well as the offending computer.
    • Self-Test for attack simulation
    • Classification of the attack based on log.
    • Automatic updates with the most current ransomware definitions.

    Contact us at https://www.razlee.com/anti-ransomware

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Sponsored Links

    Profound Logic Software:  Reach Your Modernization Goals. Register for the February 25 Webinar now!
    New Generation Software:  Ask us about Query, Reporting, and Analytics. Order a FREE Trial of NGS-IQ.
    System i Developer:  Upgrade your skills at the RPG & DB2 Summit in Dallas, March 17-19

    Reader Feedback On IBM i Wish List For 2015 DB2 Enhancements, Free Form RPG, Modernization Top Rowe’s ‘Big Hits’ List

    Leave a Reply Cancel reply

Volume 15, Number 02 -- January 27, 2015
THIS ISSUE SPONSORED BY:

WorksRight Software
SEQUEL Software
System i Developer

Table of Contents

  • Everybody Likes Shortcuts! Part 2, Playing With Blocks
  • The Powerful SQL Upsert
  • Knee-Deep In Ruby Waters

Content archive

  • The Four Hundred
  • Four Hundred Stuff
  • Four Hundred Guru

Recent Posts

  • IBM Mulls Using DataMigrator as Cloud Warehouse Pipeline
  • PowerTech AV Automatically Detects Ransomware Activity
  • Infor Puts CM3 Project On Hold
  • Four Hundred Monitor, June 29
  • IBM i PTF Guide, Volume 24, Number 26
  • Guild Mortgage Takes The 20-Year Option For Modernization
  • IBM i Licensing, Part 3: Can The Hardware Bundle Be Cheaper Than A Smartphone?
  • Guru: The Finer Points of Exit Points
  • Big Blue Tweaks IBM i Pricing Ahead Of Subscription Model
  • We Still Want IBM i On The Impending Power E1050

Subscribe

To get news from IT Jungle sent to your inbox every week, subscribe to our newsletter.

Pages

  • About Us
  • Contact
  • Contributors
  • Four Hundred Monitor
  • IBM i PTF Guide
  • Media Kit
  • Subscribe

Search

Copyright © 2022 IT Jungle

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.