Arrays and Hashes


Collapse Content

Arrays

Arrays are ordered, integer-indexed collections of objects. They are similar to ArrayLists in Java, Lists in Python and Arrays in Javascript. They can be created with the square bracket syntax []. We'll be using an array called arr in the examples:

arr = [1, 2, 3, 4, 5]
arr[2]  #=> 3

Arrays in Ruby can contain different types of items:

 misc_array= [1, "hello", false]

Arrays can be accessed by index from the beginning:

arr[0] #=> 1
arr[12] #=> nil

...or from the end:

arr[-1] #=> 5

Add an item to the end of an array with <<

 arr << 6 #=> [1, 2, 3, 4, 5, 6]

...or set the value of a specific index:

arr[3] = 17
arr[8] = 7 

The array will automatically expand to reach that index:

arr #=> [1, 2, 3, 17, 5, 6, nil, nil, 7]

More methods for getting Array info:

arr.length #=> 6
arr.first #=> 1
arr.last #=> 6

arr.include?(3) #=> true
arr.include?(9) #=> false

Ranges

Ranges are used for creating ordered sequences. There created with .. syntax:

rang = 1..5

Ranges can be converted to an array with to_a:

rang.to_a  #=> [1, 2, 3, 4, 5]

Ranges can be used as parameters to access a series of elements in an array:

 arr[1..3] #=> [2, 3, 4]

Hashes

A Hash is a dictionary-like collection of unique keys and their values. It is similar to a HashMap in Java, a Dictionary in Python and an Object in Javascript. A Hash can be created with the curly-braces {} syntax:

ha = {'color' => 'green', 'number' => 5}

=> is used to point from keys to values.

ha.keys #=> ['color', 'number']
ha.values #=> ['green', 5]

Insert items into a hash just like in an array, but with any type as the key:

 hash['price'] = 72

Hashes can instantly look up a key and return the value it points to:

hash['color'] #=> 'green'
hash['number'] #=> 5

A hash returns nil when asked for a key that doesn't exist:

hash['missing'] #=> nil

Often, symbols are used as keys:

ha2 = {:color => "blue", :number => 7}

In these cases, Ruby allows for a more concise syntax that gets rid of the => and moves the : from before the symbol to after it:

ha2 = {color: "blue", number: 7}

Regardless of the type of key, you can use it to return a value:

ha2[:color]  #=> "blue"

Tip: Both Arrays and Hashes are Enumerable. They share a lot of useful methods such as each, map, count, and more

This tutorial is based in part on LearnXinYminutes.

Challenge

What will the following code return?

arA = [1, 2, 3, 4, 5]
arA[1..2]

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

Create a Hash called num_to_day with integer keys from 1 to 7 pointing to the String name of that day of the week. For example, 1 should point to "Sunday" and 7 should point to "Saturday".

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]