You Can Do Things Other Than Math with Strings in Ruby

By Christopher Haupt

Besides mathlike operations, strings in Ruby have many other useful functions built in. As you get more familiar with programming, there will be times you want to do something more complicated, and Ruby will be there to save the day!

Imagine you needed to make a greeting appear to shout. In text, you may want to use all capital letters. But what if the variable doesn’t already have a name in capitals? You can use a string function to solve that problem:

2.2.2 :031 > "Chris".upcase
=> "CHRIS"
2.2.2 :032 > name = "Chris"
=> "Chris"
2.2.2 :033 > name
=> "Chris"
2.2.2 :034 > name.upcase
=> "CHRIS"

To use an object’s capabilities in Ruby, you follow the object with a period (also known as a dot) and then the name of the function you want to use. This technique works directly with an object like the string example above, or with a variable.

Here you’re trying to use the upcase function to convert the string to capital letters on the fly.

In Ruby, an object’s programmed capabilities or functions are known as methods. When you write code that makes an object use a method, you’re “sending a message” to that object.

Try this example:

2.2.2 :035 > greeting = "hello there"
=> "hello there"
2.2.2 :036 > greeting.capitalize
=> "Hello there"

If you forgot to capitalize the greeting (or perhaps weren’t sure if it was capitalized because you got the variable from somewhere else), you can use the string object’s capitalize method to get the job done.

The official Ruby documentation site can be a little scary when getting started. For now, know that it’s there and it’s free. There are also lots and lots of free resources on the web that will help you expand your learning. The Ruby String reference is just a small part of the available documentation. If you scan over the page, even if you don’t understand it all, you’ll see a huge number of methods that you can use in the future.