The Pragmatic Studio

Objects Everywhere

Exercises

Objective

A variable always references an object. For example, currently in the game the name variable references a string object and the health variable references an integer object:

name = "Finn"
health = 60

And we can tell objects to do things by calling methods on the objects.

In this exercise, we'll practice calling methods to print out the player's info in slightly different formats, like so:

Finn has a health of 60
FINN has a health of 60
*************Finn has a health of 60**************
Finn.......................... 60 health

Let's get to it!

1. Navigate the Docs

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. That's what the Ruby documentation is for! 📖

  1. To view the online documentation, browse to https://ruby-doc.org/ and click "Current" in the header for the current Ruby version. Then type "String" in the search field in the upper-left corner and click the first match which should be the String class.

    Then scroll through the "Methods" listed on the left-hand side and click a method name to view its documentation. Go ahead, check out a few different methods to get a feel for what a string can do.

  2. To view the same Ruby documentation from the comfort of your command line, use the ri command-line utility like so:

    ri String

    Then to narrow it down to get more information about a particular method such as capitalize, use

    ri String.capitalize

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

  3. 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.

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 and get immediate feedback!

2. Tell a String What To Do

  1. Returning to our objective, back in your studio_game.rb file change the name variable to reference the lowercase string "finn":

    name = "finn"
    

    Then when printing the player's info, capitalize the name by calling a String method on the object referenced by the name variable.

  2. Next, print the player's name in all uppercase letters.

  3. Then print the player's name capitalized and centered with asterisks as padding, like this:

    *************Finn has a health of 60**************

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

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

  4. Finally, print the player's name capitalized and left-justified, like this:

    Finn.......................... 60 health

    There are at least two ways to do this as well.

  5. As a bonus, suppose the name variable was assigned a wacky string with whitespace characters surrounding the player's name, for example:

    name = "  \n finn \t "
    

    Find and call the method to strip away those whitespace characters.

3. What Can An Integer Do?

  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 an integer, such as a player's health. Try it by opening an irb session and typing:

    >> health = 123
    >> health.reverse
    

    Hmm, why doesn't that work?

  2. Take a moment to study the error message:

    undefined method `reverse' for 123:Integer

    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 an Integer.

    Indeed, if you look up the documentation for the reverse method you'll find that it's not defined on the Integer 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 health integer again.

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

  5. Finally, just for funsies, find and call a method to raise the health to a power of 2. 💥

4. 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 _____ referenced by the _____ named name and the resulting ________ is 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.

Wrap Up

Nicely done! In this exercise you learned how to:

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

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! And we'll learn how to do that in just a jiffy.

Ruby in Rails

Rails web applications are chock full of objects! And to get anything useful done, you'll need to call methods on those objects. Here are just a few quick examples...

  • Perhaps you need to generate a URL path to a blog post by downcasing the post's title and replacing all spaces with a hyphen:

    "/blog/#{post_title.downcase.gsub(" ", "-")}"
    
  • Given a user object, you save that user to the database by calling the save method:

    user.save
    
  • And it's common to check if a user has set a password:

    user.password.empty?
    

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.