Ryan Ho

Think, Create, Do, Repeat

LinkedIn GitHub Facebook Twitter

Arrays and Hashes

October 26, 2015 | Coding

Overview

Arrays and Hashes are great tools for you to use to store and access information in an organized way. Both are ordered lists that allow you to store different types of objects (e.g. Strings, Integers, Hashes, etc.). They also allow you to access the information you stored using index integers (for arrays) and keys (for Hashes). Lets take a deeper look into both Arrays and Hashes.

Arrays

Arrays store objects, from Classes, Strings, Integers, Arrays, Hashes, etc. It is a very useful way to store and access information in an orderly manner. For example, your boss wants you to store some company data sets of monthly sales figures. You can store that information into arrays! You can also choose to store an array within an array, which makes the array class a very flexible way to store information. Here is an example of storing the numbers 1 to 10 in an array

numbers_array = [1,2,3,4,5,6,7,8,9,10]
Within this array, the values stored can be accessed in the following way:
numbers_array[0]	#returns 1
numbers_array[1]	#returns 2
Array indexing starts at 0 for the first value stored, and has index of 1 for the second value stored, so on and so forth.

Hashes

Hashes are similar to Arrays in that it stores information in an organized way as well, but it uses key/value pairs to store and access information. Instead of having an integer indexing system (like in Arrays), Hashes uses keys to store values, and these keys are unique and can only be used once. Using keys in Hashes allows more customizability in labeling compared to Arrays, providing more detailed information about the data being stored. One example is as follows:

dog_breeds = {
	    		:Sunny => "Golden Retriever"
	    		:Truffles => "Chihuahua"
	    		:Rocky => "German Shephard"
	    		}
To access the breed for Truffles, I can do the following:
dog_breeds[:Truffles]	#returns "Chihuahua"

Overall, Arrays and Hashes are great ways to store information in an organized way. Choosing one over the other ultimately depends on the context in which you are working in.

Comments box

Name:
Email:
Comments: