Skip to content

Instantly share code, notes, and snippets.

@rpearce
Last active May 10, 2022 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpearce/7664564c219ea2e8f330 to your computer and use it in GitHub Desktop.
Save rpearce/7664564c219ea2e8f330 to your computer and use it in GitHub Desktop.
Ruby Fundamentals - Data Types: Arrays and Hashes

Arrays and Hashes

If you have a list of data values, Ruby lets you store these values into a type of list called an Array. Similarly, if you have a list of properties that describe a concept, these properties and their values can be grouped together into what is called a Hash.

In this lesson, we will come to understand why these data types exist and how to use them.

Arrays — [ ]

If you have ever made yourself a grocery list, a reading list, or a travel checklist, then you probably already understand the value of creating a list and naming it separately from the other types of lists you have. With Ruby arrays, we can do the same thing.

Consider that you want to keep a list of your family members' ages, though in no particular order. Using an array and integers, that could look like this:

ages = [57, 25, 56, 28, 23]

See the [ and ] characters? These brackets are how we can create an array in just two characters! The commas (,) are used to separate one item of the list from the next.

Great work! Now let's discover how we can do more with our ages array.

Indices

Once we have our ages in a list, we will probably want to access individual ones at some point in the future and even change their values (for example, someone has a birthday). One way to retreive a value from an array is to ask for the value at a specific "index" within the array. What does index mean in this context? Looking at our ages array, we can count that there are five items in it. However, Ruby starts counting at the number 0 instead of 1, so while Ruby knows there are five items in the array, if you want to refer to a specific item, you will have to start your counting at 0. This means that when we refer to "index 0," we are referring to the first item in our list.

##########################################
# TODO: THIS MIGHT BE GOOD FOR A GRAPHIC #
##########################################

ages = [57, 25, 56, 28, 23]
# index  0   1   2   3   4

Getting a Value at an Index

Let's ask for the first item in our ages array:

ages[0] # => 57

To ask for an age value at a specific index in our ages array, we use the [ and ] bracket characters with an array index in between the two.

Tip: If you need to reference the very last element in your array, the easiest way to do so is with a negative index: ages[-1].

Setting a Value at an Index

What if we instead wanted to create an empty ages array but wanted to manually add items to it, have them keep the same order, but add them out of the order from which they appear? No problem!

ages = []
ages[2] = 56
ages[0] = 57
ages[3] = 28
ages[1] = 25
ages[4] = 23
ages # => [57, 25, 56, 28, 23]

The person at index 4 had a birthday! How can we update age 23 to 24? The same way, of course.

ages[4] = 24
# or
ages[4] += 1

push() and pop

If you need to add a value to the end of an array and have it become the last value, then you can use the push command with the value to add to the array. To remove the last item from the array, you can use pop.

ages = [57, 25, 56, 28, 23]
ages.push(40) # => [57, 25, 56, 28, 23, 40]
ages.pop # => 40
ages # => [57, 25, 56, 28, 23]

Caution! Using push and pop mutate (change) the original array. So if you push something on to the end of an array, the array's new value will include what you pushed on there. The same goes for pop, where if you use the pop command, Ruby will return the value of what was "popped" off of the array, but the array itself is now without that value. ages.pop removes the last value from the array and returns it, whereas ages[-1] simply returns it without altering the actual array at all.

length and empty?

How many items are in our ages array? We can use the length command to check for the total number of items, and if we only care to know if it does not have any items, we can ask if it is empty?.

ages = [57, 25, 56, 28, 23]
ages.length # => 5
ages.empty? # => false

Hashes — { }

If we have an array of ages ([57, 25, 56, 28, 23]), how can we know to whom each age belongs without personally knowing the people? We need a way to organize each item in the list to not just store a value for someone's age, but to also be able to store that person's name, as well. When we describe a person, we list out a number of descriptors about them ("name", "age", "hair color") and then apply values to each one of those ("Jane", 57, "blonde"). In Ruby, we can take these descriptive properties, also known as keys, and give them values in the form of a Ruby data type called a Hash.

Creating a Hash

An "empty" hash can be created by using the brace characters ({ and }) together. You can also provide default keys values like this:

{
  name: "Jane",
  age: 57,
  hair_color: "blonde"
}

# or, assigned to a variable and on one line

person = { name: "Jane", age: 57, hair_color: "blonde" }

Getting and Setting a Key's Value

When dealing with an ages array, we can access ("get") a specific index via ages[2], and we can change ("set") the value via ages[2] = 58. Getting and setting a hash key's value is very similar to how the same is done with an array:

person = { name: "Jane", age: 57, hair_color: "blonde" }

# getting the person hash's age value
person[:age] # => 57

# setting the person's age value
person[:age] = 58 # => 58

If you are confused by the colon character (:), don't be! Ruby uses something called Symbol to act as the data type for your hash keys. Symbols normally are prefixed with a colon, so when we want to ask for the age key, we simply need to prefix it with a : when using it on our person variable: person[:age].

Adding Keys and Values Later

What if you have already started with an empty hash and want to add keys and values after the fact? No problem!

person = {}
person[:name] = "Jane"
person[:age] = 57
person[:hair_color] = "blonde"
person # => {:name=>"Jane", :age=>57, :hair_color=>"blonde"}

See what person returns? It looks very similar to our hash, but it is a bit different. When it comes to hashes, :name => "Jane" is functionally equivalent to name: "Jane"; it's just that the first one is an older hash syntax.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment