Learn Ruby on Rails: the Ultimate Beginner’s Tutorial

Share this article

Interacting with Ruby Objects

Getting used to thinking in terms of objects can take some time. Let’s look at a few different types of objects, and see how we can interact with them.

Literal Objects

Literal objects are character strings or numbers that appear directly in the code, as did the number 1 that was returned in the previous section. We’ve seen numbers in action; next, let’s look at a string literal.

A string literal is an object that contains a string of characters, such as a name, an address, or an especially witty phrase. In the same way that we created the 1 literal object in the previous example, we can easily create a new string literal object, then send it a message. A string literal is created by enclosing the characters that make up the string in single or double quotes, like this:

irb> "The quick brown fox"
=> "The quick brown fox"

First, we’ll confirm that our string literal indeed belongs to class String:

irb> "The quick brown fox".class
=> String

This String object has a wealth of embedded functionality. For example, we can ascertain the number of characters that our string literal comprises by sending it the length message:

irb> "The quick brown fox".length
=> 19

Easy stuff, eh?

Variables and Constants

Every application needs a way to store information. Enter: variables and constants. As their names imply, these two data containers have their own unique roles to play.

A constant is an object that’s assigned a value once, and once only (usually when the application starts up). Constants are therefore used to store information that doesn’t need to change within a running application. As an example, a constant might be used to store the version number for an application. Constants in Ruby are always written using uppercase letters, as shown below:

irb> CONSTANT = "The quick brown fox in a constant"
=> "The quick brown fox in a constant"
irb> APP_VERSION = 5.04
=> 5.04

Variables, in contrast, are objects that are able to change at any time. They can even be reset to nothing, which frees up the memory space that they previously occupied. Variables in Ruby always start with a lowercase character:

irb> variable = "The quick brown fox in a variable"
=> "The quick brown fox in a variable"

There’s one more special (and, one might say, evil) thing about a variable — its scope. The scope of a variable is the part of the program to which a variable is visible. If you try to access a variable from outside its scope (i.e. from a part of an application to which that variable is not visible), you generally won’t be able to.

The notable exception to the rules defining a variable’s scope are global variables. As the name implies, a global variable is accessible from any part of the program. While this might sound convenient at first, usage of global variables is discouraged — the fact that they can be written to and read from any part of the program introduces security concerns.

Let’s return to the string literal example we saw earlier. Assigning a String to a variable allows us to invoke on that variable the same methods we invoked on the string literal earlier:

irb> fox = "The quick brown fox"
=> "The quick brown fox"
irb> fox.class
=> String
irb> fox.length
=> 19

Punctuation in Ruby

The use of punctuation in Ruby code differs greatly from other languages such as Perl and PHP, so it can seem confusing at first if you’re used to programming in those languages. However, once you have a few basics under your belt, punctuation in Ruby begins to feel quite intuitive and can greatly enhance the readability of your code.

Dot Notation

One of the most common punctuation characters in Ruby is the period (.). As we’ve seen, Ruby uses the period to separate the receiver from the message that’s being sent to it, in the form Object.receiver.

If you need to comment a line, either for documentation purposes or to temporarily take a line of code out of the program flow, use a hash mark (#). Comments may start at the beginning of a line, or they may appear further along, after some Ruby code:

irb> # This is a comment. It doesn't actually do anything.
irb> 1 # So is this, but this one comes after a statement.
=> 1
irb> fox = "The quick brown fox"    # Assign to a variable
=> "The quick brown fox"
irb> fox.class                      # Display a variable's class
=> String
irb> fox.length                     # Display a variable's length
=> 19

Chaining Statements Together

Ruby doesn’t require us to use any character to separate commands, unless we want to chain multiple statements together on a single line. In this case, a semicolon (;) is used as the separator. However, if you put every statement on its own line (as we’ve been doing until now), the semicolon is completely optional.

If you chain multiple statements together in the interactive shell, only the output of the last command that was executed will be displayed to the screen:

irb> fox.class; fox.length; fox.upcase
=> "THE QUICK BROWN FOX" 

Use of Parentheses

If you’ve ever delved into the source code of one of the many JavaScript libraries out there, you might have run screaming from your computer when you saw all the parentheses that are involved in the passing of arguments to methods.

In Ruby, the use of parentheses for method calls is optional in cases in which no arguments are passed to the method. The following statements are therefore equal:

irb> fox.class()
=> String
irb> fox.class
=> String

It’s common practice to include parentheses for method calls with multiple arguments, such as the insert method of the String class:

irb> "jumps over the lazy dog".insert(0, 'The quick brown fox ')
=> "The quick brown fox jumps over the lazy dog"

This call inserts the second argument passed to the insert object ("The quick brown fox ") at position 0 of the receiving String object ("jumps over the lazy dog"). Position 0 refers to the very beginning of the string.

Method Notation

Until now, we’ve looked at cases where Ruby uses less punctuation than its competitors. In fact, Ruby makes heavy use of expressive punctuation when it comes to the naming of methods.

A regular method name, as we’ve seen, is a simple, alphanumeric string of characters. If a method has a potentially destructive nature (for example, it directly modifies the receiving object rather than changing a copy of it), it’s commonly suffixed with an exclamation mark (!).

The following example uses the upcase method to illustrate this point:

irb> fox.upcase
=> "THE QUICK BROWN FOX"
irb> fox
=> "The quick brown fox"
irb> fox.upcase!
=> "THE QUICK BROWN FOX"
irb> fox
=> "THE QUICK BROWN FOX"

Here, the contents of the fox variable have been modified by the upcase! method.

Punctuation is also used in the names of methods that return boolean values. A boolean value is a value that’s either true or false; these values are commonly used as return values for methods that ask yes/no questions. Such methods end in a question mark, which nicely reflects the fact that they have yes/no answers:

irb> fox.empty?
=> false
irb> fox.is_a? String
=> true

These naming conventions make it easy to recognize methods that are destructive, and those that return boolean values, making your Ruby code more readable.

Go to page: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
Patrick LenzPatrick Lenz
View Author

Patrick has been developing web applications for ten years. Founder and lead developer of the freshmeat.net software portal, he and his Rails consultancy and application development company, limited overload were responsible for a major relaunch of Germany's biggest infotainment community. Patrick lives in Wiesbaden, Germany. His weblog can be found at poocs.net.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week