Ruby Fundamentals: Manipulating Variables

Free Ruby on Rails Tutorial

Explore the power of Ruby on Rails in creating and manipulating strings, understanding substrings, ranges, and regular expressions with this comprehensive tutorial. Master the use of simple string methods such as changing case, and familiarize yourself with the flexibility of Ruby's string class.

This exercise is excerpted from Noble Desktop’s past web development training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this Ruby on Rails tutorial:

Creating strings in Ruby, Simple string methods: changing case, Substrings, Ranges, Comparing strings, Regular expressions

Exercise Overview

In this exercise, we will look at strings. In Ruby, strings are objects of the String class, which means they have a number of methods associated with them. (You can read all about the methods at ruby-doc.org.) Exciting stuff! Let’s get to learning.

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Creating Strings in Ruby

  1. If you closed Terminal, closed the window, or exited IRB, open a Terminal window and type the irb command.

  2. Strings are simply blocks of text. A string has a name and a value, and you refer to it by its name to get the value. Type the following to create and then call a string:

    name = "fluffy"
    name
    

    Terminal should return "fluffy". We have just seen a simple string in action. The variable is called name, and "fluffy" is the value that it returned.

Simple String Methods: Changing Case

  1. Type the following:

    name.capitalize
    

    Terminal should return a capitalized string: "fluffy".

  2. Type:

    name.upcase
    

    Terminal should return the entire string in upper case: "FLUFFY".

  3. Type:

    name.length
    

    Terminal should return 6, the number of characters in the string.

  4. You can easily chain methods together in Ruby. They are processed from left to right. Try typing this:

    name.capitalize.reverse
    

    Terminal will capitalize and then reverse the string, returning "yffulF".

  5. Type:

    name.reverse.capitalize
    

    In this case, as you might expect, since Terminal works from left to right, it reverses and then capitalizes the string, returning "Yffulf".

  6. But wait­—are these changes permanent? Check by typing:

    name.capitalize 
    name
    

    Terminal will return "fluffy" on the second line, so we can see it has reverted to the uncapitalized version.

  7. Exclamation points play an important role in string methods: adding them to the end of a method makes the method permanent. To see this in action, type the following:

    name.capitalize!
    

    Terminal will again return a capitalized "Fluffy".

  8. Check if the change is permanent by typing:

    name
    

    Great! Terminal will return "Fluffy" because this time, thanks to the magical exclamation point, the change has become permanent.

Substrings

Arrays are essentially lists. A string is essentially a list of characters, so it’s also an array. We can use arrays to find characters within a string and get those substring values using [brackets]. We’ll explore arrays in greater depth at a later point, but for now you just need to know this: a single number in [brackets] returns a single character at a given position in the string. Like most programming languages, the first item is 0, not 1.

  1. This will make more sense once you see how arrays behave. Try typing:

    name[0]
    

    IRB should return "F" since it is the first letter of "Fluffy" (remember that we’re counting from 0, instead of 1).

    TIP: To reload your last Terminal command you can press the Up Arrow key. You can then use your Left and Right Arrow keys to move within the command. This may save you some typing as you go through the following steps.

  2. Type the following:

    name[1]
    

    Terminal should return the second character of the string, "l".

  3. Type the following:

    name[2]
    

    Terminal should return "u"­—you get the picture.

  4. If you provide two numbers, IRB will return the portion of the string starting at the first number, with a length equal to the second number. For example, try typing this:

    name[0,2]
    

    Terminal should return "Fl", starting the substring value array at position zero and returning two characters total.

  5. Type the following:

    name[0,4]
    

    Terminal should return "Fluf", starting at position zero and returning four characters total.

  6. Try typing this:

    name[1,4]
    

    Terminal should return "luff", the middle four characters of the string.

  7. Type the following:

    name[0,0]
    

    Terminal should return an empty string that looks like this: "" since a string with zero length will have no characters. This is fairly straightforward for anyone who has any prior programming experience, so that’s enough playing with substrings for now!

Ranges

To get the portion of a string between positions, you need to use a unique Ruby component called a range. A range is just two numbers separated by two or three periods, like an ellipsis. Keep in mind that we begin with 0 (that is, the first letter of a word occupies position 0).

  1. Type the following:

    name[0..2]
    

    Terminal should return "Flu", that is, all of the characters starting at position 0 and running to position 2 (which is the third character).

  2. Try typing the following:

    name[0..4]
    

    Terminal should return "Fluff" in this case, that is, all the characters in the string starting at position 0 and running to position 4 (five characters total).

  3. Type the following:

    name[1..3]
    

    Terminal should return "luf", the middle three characters in the string, occupying positions 1, 2, and 3.

  4. When using ranges, TWO periods includes the last position in the range. THREE periods does NOT include the last position in the range. Let’s try it, type:

    name[0...2]
    

    Terminal should return "Fl", a substring array including the characters at positions 0 and 1, but not including the character at position 2.

  5. Type the following (notice we’re using two periods!):

    name[0..5]
    

    Terminal should return "Fluffy", all six characters in the string, because TWO periods includes the last position in the range.

  6. Type the following (with three periods):

    name[0...5]
    

    Terminal should return "Fluff", only up to position five, since THREE periods do not include the last position in the range.

Comparing Strings

  1. There are a number of ways to compare strings. The simplest one is to check whether two strings are equivalent. Type the following:

    name = "Fluffy" 
    not_allowed = "Fluffy"
    if name == not_allowed
       "Fluffy is not allowed in here."
       end
    

    Terminal will evaluate this as true, and print the if statement, "Fluffy is not allowed in here." This is one of the simplest ways of checking if two strings are equivalent.

  2. Let’s look at some slightly more complex and powerful ways of comparing strings. Type the following:

    my_story = "I once had a cat named Fluffy."
    my_story.include? "Fluffy"
    

    Terminal should evaluate this as true, because the string does include "Fluffy".

  3. On the other hand, try typing the following:

    my_story.include? "George"
    

    Terminal should evaluate this as false, because the word "George" doesn’t appear in the my_story string.

  4. You can also use the methods start_with and end_with to add specificity when comparing strings. Type the following:

    "Fluffy is the best cat".start_with? "Fluffy"
    

    Terminal should evaluate this as true.

  5. Type the following:

    "Fluffy is the best cat".end_with? "Fluffy"
    

    Terminal should evaluate this as false.

Regular Expressions

More sophisticated string comparisons and replacements typically involve something called regular expressions (“regex” for short). Regular expressions are like an advanced find/replace. They are written between two forward slashes (/), and are used to perform partial matches. In other words, they identify parts of a string that meet a given pattern.

  1. Type the following miniature biography for Fluffy:

    bio = "Fluffy the Cat is dictator forever over Catopia. All hail Fluffy!"
    
  2. Suppose that Fluffy gets deposed and George takes over Catopia. We need to replace the name in this bio quickly and easily. We will use the gsub method, which replaces any matches it finds of a regular expression within a given string. Type the following bold code:

    bio.gsub(/Fluffy/,"George")
    

    Ruby recognizes /Fluffy/ as a regular expression (because it is written between two forward slashes). Terminal will replace all instances of "Fluffy" with "George" to return the modified bio: "George the Cat is dictator forever over Catopia. All hail George!" This shows how well a regular expression can be used to perform a partial match!

  3. That’s enough for this exercise, but you’ll continue using the Terminal and IRB in the next exercise, so you can leave them open and ready.

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram