Learn Ruby on Rails: the Ultimate Beginner’s Tutorial

Share this article

Ruby Core Classes

We’ve already talked briefly about the String and Fixnum classes in the previous sections, but Ruby has a lot more under its hood. Let’s explore!

Arrays

We use Ruby’s Arrays to store collections of objects. Each individual object that’s stored in an Array has a unique numeric key, which we can use to reference it. As with many languages, the first element in an Array is stored at position 0 (zero).

To create a new Array, simply instantiate a new object of class Array (using the Array.new construct). You can also use a shortcut approach, which is to enclose the objects you want to place inside the Array in square brackets.

For example, an Array containing the mileage at which a car is due for its regular service might look something like this:

irb> service_mileage = [5000, 15000, 30000, 60000, 100000]
=> [5000, 15000, 30000, 60000, 100000]

To retrieve individual elements from an Array, we specify the numeric key in square brackets.

irb> service_mileage[0]
=> 5000
irb> service_mileage[2]
=> 30000

Ruby has another shortcut, which allows us to create an Array from a list of Strings: the %w( ) syntax. Using this shortcut saves us from having to type a lot of double-quote characters:

irb> available_colors = %w( red green blue black )
=> ["red", "green", "blue", "black"]
irb> available_colors[0]
=> "red"
irb> available_colors[3]
=> "black"

In addition to facilitating simple element retrieval, Arrays come with an extensive set of class methods and instance methods that ease data management tasks tremendously.

empty? returns true if the receiving Array doesn’t contain any elements:

 irb> available_colors.empty?
=> false

size returns the number of elements in an Array:

irb> available_colors.size
=> 4
first and last return an Array's first and last elements, respectively:

irb> available_colors.first
=> "red"
irb> available_colors.last
=> "black"

delete removes the named element from the Array and returns it:

irb> available_colors.delete "red"
=> "red"
irb> available_colors
=> ["green", "blue", "black"]

The complete list of class methods and instance methods provided by the Array class is available via the Ruby reference documentation, which you can access by entering the ri command into the terminal window (for your operating system, not the Ruby shell), followed by the class name you’d like to look up:

$ ri Array

Oh, and ri stands for ruby interactive, in case you’re wondering. Don’t confuse it with irb.

Hashes

A Hash is another kind of data storage container. Hashes are similar, conceptually, to dictionaries: they map one object (the key — for example, a word) to another object (the value — for example, a word’s definition) in a one-to-one relationship.

New Hashes can be created either by instantiating a new object of class Hash (using the Hash.new construct) or by using the curly brace shortcut shown below. When we define a Hash, we must specify each entry using the key => value syntax.

For example, the following Hash maps car names to a color:

irb> car_colors = {
irb>   'kitt' => 'black',
irb>   'herbie' => 'white',
irb>   'batmobile' => 'black',
irb>   'larry' => 'green'
irb> }
=> {"kitt"=>"black", "herbie"=>"white", "batmobile"=>"black",
"larry"=>"green"}

To query this newly built Hash, we pass the key of the entry we want to look up in square brackets, like so:

irb> car_colors['kitt']
=> "black"

All sorts of useful functionality is built into Hashes, including the following methods:

empty? returns true if the receiving Hash doesn’t contain any elements:

irb> car_colors.empty?
=> false

size returns the number of elements in a Hash:

irb> car_colors.size
=> 4

keys returns all keys of a Hash as an Array:

irb> car_colors.keys
=> ["kitt", "herbie", "larry", "batmobile"]

values returns all values of a Hash as an Array, although care should be taken with regards to the order of the elements (keys in a Hash are ordered for optimal storage and retrieval; this order does not necessarily reflect the order in which they were entered):

irb> car_colors.values
=> ["black", "white", "green", "black"]

There are lots more — for the complete list of class methods and instance methods provided by the Hash class, consult the Ruby reference documentation.

Strings

The typical Ruby String object — yep, that very object we’ve been using in the past few sections — holds and manipulates sequences of characters. Most of the time, new String objects are created using string literals that are enclosed in single or double quotes. The literal can then be stored in a variable for later use:

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

If the string literal includes the quote character used to enclose the string itself, it must be escaped with a backslash character ():

irb> 'I'm a quick brown fox'
=> "I'm a quick brown fox"
irb> "Arnie said, "I'm back!""
=> "Arnie said, "I'm back!""

An easier way to specify string literals that contain quotes is to use the %Q shortcut, like this:

irb> %Q(Arnie said, "I'm back!")
=> "Arnie said, "I'm back!""

String objects also support the substitution of Ruby code into a string literal via the Ruby expression #{}:

irb> "The current time is: #{Time.now}"
=> "The current time is: Wed Aug 02 21:15:19 CEST 2006"

The String class also has rich embedded functionality for modifying String objects. Here are some of the most useful methods:

gsub substitutes a given pattern within a String:

irb> "The quick brown fox".gsub('fox', 'dog')
=> "The quick brown dog"

include? returns true if a String contains another specific String:

irb> "The quick brown fox".include?('fox')
=> true

length returns the length of a String in characters:

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

slice returns a portion of a String:

irb> "The quick brown fox".slice(0, 3)
=> "The"

The complete method reference is available using the ri command-line tool:

$ ri String

Numerics

Since there are so many different types of numbers, Ruby has a separate class for each, the popular Float, Fixnum, and Bignum classes among them. In fact, they’re all subclasses of Numeric, which provides the basic functionality.

Just like Strings, numbers are usually created from literals:

irb> 123.class
=> Fixnum
irb> 12.5.class
=> Float

Each of the specific Numeric subclasses comes with features that are relevant to the type of number it’s designed to deal with. However, the following functionality is shared between all Numeric subclasses:

integer? returns true if the object is a whole integer:

irb> 123.integer?
=> true
irb> 12.5.integer?
=> false

round rounds a number to the nearest integer:

irb> 12.3.round
=> 12
irb> 38.8.round
=> 39

zero? returns true if the number is equal to zero:

irb> 0.zero?
=> true
irb> 8.zero?
=> false

Additionally, there are ways to convert numbers between the Numeric subclasses. to_f converts a value to a Float, and to_i converts a value to an Integer:

irb> 12.to_f
=> 12.0
irb> 11.3.to_i
=> 11

Symbols

In Ruby, a Symbol is a simple textual identifier. Like a String, a Symbol is created using literals; the difference is that a Symbol is prefixed with a colon:

irb> :fox
=> :fox
irb> :fox.class
=> Symbol

The main benefit of using a Symbol instead of a String is that a Symbol contains less functionality. This can be an advantage in certain situations. For example, the car_colors Hash that we looked at earlier could be rewritten as follows:

car_colors =
:kitt => 'black',
:herbie => 'white',
:larry => 'green',
:batmobile => 'black'
}

Objects of class String can be converted to Symbols, and vice-versa:

irb> "fox".to_sym
=> :fox
irb> :fox.to_s
=> "fox"

We’ll use Symbols frequently as we deal with Rails functionality in successive chapters of this book.

nil

I promised earlier that I’d explain nil values — now’s the time!

All programming languages have a value that they can use when they actually mean nothing. Some use undef; others use NULL. Ruby uses nil. A nil value, like everything in Ruby, is also an object. It therefore has its own class: NilClass.

Basically, if a method doesn’t return anything, it is, in fact, returning the value nil. And if you assign nil to a variable, you effectively make it empty. nil shows up in a couple of additional places, but we’ll cross those bridges when we come to them.

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