The Pragmatic Studio

Variables and Objects

Exercises

Objective

At this point, we really only have one complete player: larry with a health of 60. Our other players—curly and moe—haven't yet been assigned a health. In this exercise, we'll give them some life and also add a fourth player. The goal is to print out each player's name and health with a slightly different format, like so:

Larry has a health of 60.
CURLY has a health of 125.
*************Moe has a health of 100.*************
Shemp........................... 90 health

Along the way we'll practice assigning objects to variables, calling methods on those objects, and finding documentation on methods in Ruby's standard library.

1. Player #1: Larry

As our game stands now, we have two variables holding onto the name and health of the first player:

name1 = "larry"
health1 = 60

Our first formatting task is to capitalize the name.

  1. We've seen a few string methods, but we've barely scratched the surface of what Ruby strings can do. Thankfully, you don't have to remember all the string-related methods. The ri command-line utility allows you to view information about Ruby classes, modules, and methods from the comfort of your command line. Use ri to view the RDoc documentation for the String class.

    Note: If you don't have the RDoc documentation installed locally, you can use the online documentation instead. In the search field in the top-left corner, type "String" and then click on the first "String" result.

    The instance methods are the methods that you can call on a String object.

    To exit the ri session, either press the q key to exit immediately or press the spacebar repeatedly to scroll through to the end.

    Windows Users: If you see funny ANSI characters in the output generated by ri, a quick fix is to install ANSICON.

  2. Now narrow it down to get more information about the capitalize method.

    The documentation usually includes example uses of each method. Reading them is one thing, but even better is to type an example into an irb session and run it for yourself. It's a great way to learn new methods... with immediate feedback!

    Tip: Alternatively, you can start ri in interactive mode with the -i option, like so:

    ri -i

    You should see an interactive prompt where you can type the classes and methods you're looking for and use Tab for autocompletion. For example, type String.cap and then hit the Tab key to see the matching methods. To select a matching method, hit Return. When you're done reading the documentation for a particular class or method, you end up back at the prompt for more searching. To exit, simply enter a blank line.

  3. Finally, returning to our objective, back in your studio_game.rb file change how the first player is printed so his name is capitalized. Using the two variables above, here's the output you want:

    Larry has a health of 60.

2. Player #2: Curly

For our second player, we want to print his information with the name in all uppercase letters.

  1. Create variables for a second player with the name "curly" and an initial health of 125. Then use those variables to print his information like this:

    CURLY has a health of 125.

    If you don't remember the method to capitalize all the characters in a String, don't hesitate to use ri again to look it up.

  2. Now it's time to experiment a little. Add two lines to the bottom of the program file: change Curly's health variable to point to Larry's health variable and print out Curly's information again.

    What do you expect to see? Re-run the program.

  3. Finally, add a few more lines to the bottom of the program. Reassign Larry's health variable to be 30. Then print out the name and health of both players again.

    What result do you expect for Larry and Curly now? Re-run the program.

    The assignment of variables can be a bit tricky, especially when variables reference other variables. You should now have:

    Larry has a health of 30.
    CURLY has a health of 60.

    Make sure you understand why this works before moving on. Don't hesitate to go back and watch the part in the video about the variables my_favorite_movie and your_favorite_movie if you need help. Or grab a sharpie and a napkin and draw it out for yourself if that helps.

3. Player #3: Moe

The third player's information needs to be printed so that it's all centered and padded with asterisks.

  1. Use the documentation to find the method that centers a string. Note that the first parameter (the length) is required, but the second parameter for the character to use as padding is optional. Try the examples in irb to get a feel for how the method works.

  2. Create variables for a third player with the name "moe" and an initial health of 100. Then use those variables to print his information like so:

    ************Moe has a health of 100.************

    There are at least two ways to do this, so experiment a little before looking at the answer.

4. Player #4: Shemp

  1. Create a fourth player named "shemp" with an initial health of 90. Use variables to print out his information with the name capitalized and left-justified, like this:

    Shemp........................... 90 health

    There are at least two ways to do this, so experiment a little before looking at the answer.

5. Reverse It

  1. In the video, we used the reverse method to print a reversed version of the string "Goonies". What happens if you try to reverse a number, such as a player's health. Try it by opening an irb session and typing:

    >> 123.reverse
    

    Hmm, why doesn't that work?

  2. Take a moment to study the error message:

    NoMethodError: undefined method `reverse' for 123:Fixnum

    Any time you see an error like this, take the time to read it. This is Ruby's way of trying to help us understand what went wrong. And in this case, the error is quite helpful. It's saying that it couldn't find a reverse method to call on the object 123, which is a Fixnum.

    Indeed, if you look up the documentation for the reverse method you'll find that it's not defined on the Fixnum class. So even though you can call methods on objects, only certain methods are defined on certain classes of objects.

  3. We know we can reverse a string, so how could we convert a number object to a string object? It turns out that all objects in Ruby have a to_s method that converts the object to its string representation. Using this tip, try chaining methods together to reverse the number 123 again.

  4. How then would you convert the reversed string back to an integer?

6. Vocabulary Quiz

Learning to program can feel a bit like learning a foreign language. Here are a couple sentences to help you practice your new language skills.

  1. In the following line of code, capitalize is a _______ called on the _____ named name and assigned to the ________ named text.

    text = "#{name.capitalize} has a health of #{health}."
    
  2. In the case of the line of code below, center is a _______ that takes two __________.

    puts text.center(50, '*')
    

Solution

The full solution for this exercise is in the variables-objects directory of the code bundle.

Bonus Round

Time Method

You've learned how to use the documentation and call methods on strings and numbers. The Ruby standard library has a host of other classes that you can use in your programs, as well.

For example, the Time class is useful for working with dates and times. Unlike strings and numbers, which we created using literal values, you create a new Time object like this:

current_time = Time.new

The Time class has a method called strftime that can format the time in a variety of ways. Check out the method's documentation and play around with it in irb until you've got the hang of it.

Then, back in your studio_game.rb file, print the date and time the game started so that it's formatted like this:

The game started on Tuesday 03/06/2022 at 10:43AM

Fundraising Program

If you're building the fundraising program, your next step is to assign a funding amount to each project. In other words, how much funding does each project have so far? Then, experiment with different formats for printing out each project's name and funding amount.

The solution for this bonus app exercise is in the variables-objects directory of the code bundle.

Wrap Up

Nicely done! Now you have all the game players introducing themselves. In this exercise you learned how to:

  • assign variables
  • call built-in methods
  • pass parameters to methods
  • chain together multiple method calls
  • look up methods in the Ruby documentation

But what if you want to do something for which there isn't a built-in Ruby method? Well, then it's time to write your own method! We'll do that in the next section.

For a quick summary on strings and variables, as well as summaries for the upcoming modules, download the course summary PDF for easy reference.

All course material, including videos and source code, is copyrighted and licensed for individual use only. You may make copies for your own personal use (e.g. on your laptop, on your iPad, on your backup drive). However, you may not transfer ownership or share the material with other people. We make no guarantees that the source code is fit for any purpose. Course material may not be used to create training material, courses, books, and the like. Please support us by encouraging others to purchase their own copies. Thank you!

Copyright © 2005–2024, The Pragmatic Studio. All Rights Reserved.