The Rubyist Historian: Arrays and Hashes

To review, we’ve learned how to create functions, call upon methods, create classes, and generate basic programs in Ruby. We’ll now be moving into creating arrays and hashes.

Arrays

Ruby arrays and hashes are indexed collections that store objects. Arrays and hashes can contain different object types: strings, integers, and floating-point numbers. Arrays tend to be more efficient in accessing elements, but hashes provide greater flexibility.

Arrays are initiated between square brackets. Inside of an array you can access individual elements by calling upon its index. Note that Ruby begins its index with zero.

my_array = ["Ambrose", "White", "Worster"]

# print the items in the array by calling
# their index
puts my_array[0] # => Ambrose
puts my_array[1] # => White
puts my_array[2] # => Worster

There is no practical limit as to how many things an array can hold. And, as mentioned above, there is no problem with mixing types of array elements. You could just as easily write:

my_array = [ 42, "books", 3.14 ]
puts my_array[0] # => 42
puts my_array[1] # => books
puts my_array[2] # => 3.14

Note that strings must be enclosed in single or double quotes.

Arrays also include two operators. The first is pop, which removes the item on the right side (or, the end of the array). The other is shift, which removes items on the left side (beginning) of the array.

my_array = ["Ambrose", "White", "Worster"]

array_change = puts my_array.pop
array_change2 = puts my_array.shift

puts array_change # => Worster
puts array_change2 # => Ambrose

We can also add things to the array by using the push and unshift methods. The push method adds items to the end (or right side of) the array while the unshift method adds things to the beginning of (or left side of) the array.

my_array = ["Ambrose", "White", "Worster"]

array_new = my_array.push("Ulrich")
array_new = my_array.unshift("West")

puts "The array contains #{array_new.inspect}"

Arrays can also be created much more simply by using the shortcut %w, which removes the need for all those quotes and commas:

# array-shortcut.rb

a = [ 'Apple', 'Microsoft', 'Linux', 'Solaris' ]
a[0] # => "Apple"
a[1] # => "Microsoft"

# we can achieve the same thing by using:

a = %w{ Apple Microsoft Linux Solaris }
a[0] # => "Apple"
a[1] # => "Microsoft"

We can create an empty array by calling Array.new. The array is defining what objects must look like. Remember that every class has a special method called new, and new is a special method called a constructor. By calling Array.new, we’re asking Ruby to create an empty object. So, lets create an empty array and populate it with data:

authors = Array.new

authors.push("Hemingway")
authors.push("Faulkner")
authors.push("Whitman")

puts authors

The program should print the contents of the array to the screen.

Hashes

Ruby hashes share similarities with arrays but operate differently and have different syntaxes. Hashes use braces rather than brackets. Most importantly hashes must provide two objects for every entry, one for the key and one for the value. The key and the value are separated by a =>.

So, lets say we wanted to map author ratings. The hash setup would look like this:

authors = {
    'Hemingway'     =>   'five_stars',
    'Stephenson'    =>   'four_stars',
    'Heppler'       =>   'one_star',
    'Whitman'       =>   'five_stars',
    # key           =>    value
}

The item to the left of => is the key while item on the right is its corresponding value. Keys in a hash must be unique (we cannot have two “Stephenson,” for example) but values can repeat. Hashes are indexed with the same square brackets as arrays. To print results from the above hash, we could write:

puts authors['Whitman'] # => five_stars
puts authors['Stephenson'] # => four_stars

Also, like arrays, you can create an empty hash with Hash.new and inject data into it. For example:

my_hash = Hash.new()

hash['Dickenson'] = 'three_stars'

Hashes have one significant advantage over arrays: they use any object as an index. And, if you’re using Ruby 1.9, Ruby also remembers the order in which you add items to the hash. When you iterate over entries, Ruby will return them in the correct order. Hashes are a frequently used data structure in Ruby.

Additional Resources

Visit the Rubyist Historian Table of Contents for more sections, and check out the Github repository for an archive of all the code examples.

See something that’s wrong? Examples that don’t work? Explanations that are unclear or confusing? Embarrassing typographic errors? Drop me an email at jason.heppler+feedback at gmail and I’ll fix things right up!

Topic structure, examples, and explanations for the Rubyist Historian are inspired by, credited to, and drawn from Stephen Ramsay and his course Electronic Text.

January 04, 2011 @jaheppler

Tagged in: coderuby