Using Array and Hash Built-in and Related Methods

By Christopher Haupt

Part of Ruby For Kids For Dummies Cheat Sheet

Ruby has many built-in classes, but perhaps the most useful objects used for holding other data are the container classes Array and Hash. You can save a lot of time coding if you remember that each of these classes has many useful methods for accessing and manipulating their contents.

Array basics

Use arrays for lists of information that you want to keep in order. Create a new empty array with empty square brackets [] and an array with contents by placing them between the square brackets, separated by commas:

empty_array = []
my_array = ["red", "green", "blue"]

Access items in an array using the index (position) of the item, starting with the first position whose number is zero (0):

2.1.2 :009 > my_array = ["red", "green", "blue"]
 => ["red", "green", "blue"]
2.1.2 :010 > puts my_array[0]
Method Name Purpose
my_array[1] Accesses the array in my_array at
index 1
length Returns the length of the array
<<, push Adds an object at the end of the array
pop Removes an object at the end of the array
insert Adds an object at the start of the array
shift Removes an object at the start of the array
sort Sorts the array
shuffle Randomizes positions of objects in the array
sample Picks a random object from the array
each Loops over the array, returning each element
join Combines each element into a string

Hash basics

Use hashes when you have information that you want to be able to look up by name (like a contact book), and order is not necessarily important. Create a new hash with empty curly brackets {} and a new hash with contents by providing a key and value separated by “hash rockets” (=>), and each key/value pair separated by commas:

2.1.2 :018 > empty_hash = {}
 => {}
2.1.2 :019 > contact_hash = {"mom" => 1234, "dad" => 4567}
 => {"mom"=>1234, "dad"=>4567}
Method Name Purpose
contact_hash[“mom”] Accesses the hash in the contact_hash
variable using key “mom” and returns its
contact_hash[“sis”] =
Adds new value to the hash stored in the contact_hash variable using key sis
length Returns how many key/value pairs are stored in the hash
include? Checks if a key exists in the hash
keys Returns an array of all the keys in the hash
values Returns an array of all the values in the hash
empty? Returns true if the hash is empty
each Loops over each key/value pair in the hash, returning each
merge Combines two hashes into one hash, possibly overwriting the
first hash’s keys with the second hash’s keys