dreamsys software

Ruby Scripting Tutorial


TOC | Introduction | Variables | If/Else | OptionParser | Looping | Functions | Classes | Strings | Lists & Maps | Shell

Classes


When your scripts start to grow and your set of functions grow, you will start to notice that many of your functions are related, they work on data that is common between them and they really represent an entity collectively. This is where it is usually a good idea to create a class. Let's say that our program, deals with a user name, age, birth date, height, weight and variables like that and there are methods in our program such as readUserAge, readUserName, updateUserAge, etc. A good place to start would be to add a class "User" which is done by using the class keyword.

Now let's create a simple script which will ask the user for information on a user, store it to a file and load the user info from the file. We will have it run with two options, one is that the user enters the info, and another is that it just loads the user from the file and displays it.

#!/usr/bin/ruby

isRead = ARGV.length > 0 and ARGV[0] == 'READ'

ARGV.clear

class User
    @name = ""
    @age = 0
    @height = 0
    @weight = 0

    def readInput(prompt)
        print prompt
        return gets.chomp
    end

    def display()
        puts ''
        puts 'User Information:'
        puts 'User Name  : ' + @name
        puts 'User Age   : ' + String(@age)
        puts 'User Height: ' + String(@height)
        puts 'User Weight: ' + String(@weight)
    end

    def loadFromInput()
        @name = readInput('Enter User Name: ')
        @age = Integer(readInput('Enter Age: '))
        @height = Float(readInput('Enter Height (in feet): '))
        @weight = Integer(readInput('Enter Weight: '))
    end

    def save()
        f = File.new('user.info','w')
        f.puts(@name)
        f.puts(String(@age))
        f.puts(String(@height))
        f.puts(String(@weight))
        f.close()
    end

    def loadFromFile()
        f = File.new('user.info', 'r')
        @name = f.readline
        @age = Integer(f.readline)
        @height = Float(f.readline)
        @weight = Integer(f.readline)
    end
end

theUser = nil

if isRead
    theUser = User.new()
    theUser.loadFromFile()
else
    theUser = User.new()
    theUser.loadFromInput()
    theUser.save()
end

theUser.display()

the first new thing you will run into here is the keyword class, which is used to define a new class called "User". Under this we first create the variables which belong to the class. What does the user have? It has a name, age, height and weight. Instance variables for the class must start with the @ symbol. Next we define the methods which will work on the user. What do we want to do with a user? We want to load it from a file, load it from user input, save it and display it. So there are methods for each of these operations.

We declare class methods the same as we do regular methods except that they are under the class level, The methods can be declared in any order but here we have ordered them in the order that they will typically be called.

In the display() function, we are simply printing the data of the class. The loadFromInput() function uses the readInput function that we created to load the user info from the console input.

The save() method uses a new class, File, which can be used to open a file for reading or writing. In the save method, we use 'w' as the 2nd parameter, which indicates opening the file as the first parameter in "write" mode. Then we continue to call the method puts on the file object returned to write each of the variables followed by a return.

Finally, the loadFromFile() method will open the file in read mode by using the parameter 'r'. It will then use the function readline to read each of the variables from the file.

Below the class we show how the class is actually used. First we initialize the "theUser" variable with the nil keyword meaning that it is not yet created. Now we check if there is a parameter sent to the script with the text "READ", if so we will read from the file that was created when the user was saved, if not then we will ask the console for input and create and save the user.

So now, let's run the script once to create the user and then again to read the user from the file:

$ ./userTest.rb
Enter User Name: Joe
Enter Age: 25
Enter Height (in feet): 5.9
Enter Weight: 170

User Information:
User Name  : Joe
User Age   : 25
User Height: 5.9
User Weight: 170
$ ./userTest.rb READ

User Information:
User Name  : Joe
User Age   : 25
User Height: 5.9
User Weight: 170

Next you will learn how to manipulate strings.

Prev (Functions) | Next (Strings)