dreamsys software

Ruby Scripting Tutorial

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

String Manipulation (trim, substring, etc)

One of the powerful features of Ruby is its ease of use in string manipulation. Operations such as substring, split, trim and other common string manipulations are easy under Ruby.

Here we will give a simple example that shows many of these operations.


strUsers = 'rpulley  ,    jsmith, svai,  jsatriani    ,ymalmsteen    '
arrUsers = strUsers.split(',')

for user in arrUsers
    trimUser = user.strip()
    trimUserR = user.rstrip()
    trimUserL = user.lstrip()

    firstInitial = trimUser[0,1]
    lastInitial = trimUser[1,1]
    lastName = trimUser[1..-1]

    puts 'User : \'' + user + '\''
    puts 'LTrim: \'' + trimUserL + '\''
    puts 'RTrim: \'' + trimUserR + '\''
    puts ' Trim: \'' + trimUser + '\''

    puts 'First Initial: ' + String(firstInitial)
    puts 'Last Initial: ' + lastInitial
    puts 'Last Name: ' + lastName

    puts ''

So in the first line, we have a simple string, which has a list of User IDs separated by commas. These user IDs are in the format first initial followed by last name, there is also some noise in the form of spaces around some of the names. This happens very often in programming situations, especially when dealing with databases. The common way to deal with this is to "trim" the strings. In Ruby trims are referred to as stripping, which strips the whitespace from the string. The first thing we need to do, however, is to first get this string into an array, so we use the string split function to split the string into several substrings based on a given token, which we give the ',' as a parameter for.

Now we have an array of user strings in the variable arrUsers. Now that we have this array, we can simply use a for loop to iterate through all of the users. The first thing we need to do with each user is get rid of the whitespace noise around the user ID. This is done with Ruby's string strip function. This function will strip any whitespace off the start and end of the string. If you only want to strip whitespace off the beginning of a string, you can use lstrip (left strip). Likewise for stripping off of just the end of the string you can use rstrip (right strip).

Now that we have the user ID cleaned of the whitespace, we will want to substring to get the first initial, last initial and last name from the user ID. Ruby doesn't have an exact string substring function, instead you will use the index operator []. Inside of the brackets, you will put the start and end position to substring separated by a comma.

There are some essential data structures which are supported in Ruby, such as Lists and Maps, which we will cover in the next section.

Prev (Classes) | Next (Lists & Maps)