Hash Browns

person 1 = { first: "Papa", last: "Jah" }  
{:first=>"Papa", :last=>"Jah"} 
person 2 = { first: "Mama", last: "Jah" }  
{:first=>"Mama", :last=>"Jah"} 
person 3 = { first: "Jah", last: "Jah" }  
{:first=>"Jah", :last=>"Jah"} 

params = { father: person1, mother: person2, child: person3 }  
{:father=>{:first=>"Papa", :last=>"Jah"}, :mother=>{:first=>"Mama", :last=>"Jah"}, :child=>{:first=>"Jah", :last=>"Jah"}} 

params[:father][:first]  # verify it has the right value  
=> "Papa"

Working with rails you will see a lot of hashes. It’s an efficient way to store data from your web application in a particular way. A common example where you would use a hash in your application is in the collection of user data that you have for your website.

When users sign up for your website you will undoubtedly collect a heap of information regarding that particular person. Name, address, email, telephone number, gender, date of birth and the list goes on. Some of this data will be numeric, alphabetic and alphanumeric so you need a cohesive way to store this relevant data for each person.

Hashes allow you to do that by creating a “hash” with information that is specific to each user/ID. As seen in my example above I initially created three separate hashes called person1, person2 and person3. I combined this hash into one has called “params” which can be described as my family hash with father/mother/child all being associated to the relevant individual hashes. I can now access this data very easily by pointing the key-value relationship of the hash. E.g. if I wanted to see my father’s first name I would type:

params[:father][:first] (as shown above).

There are 3 different ways you can create a hash:

#1. Create an empty hash first using the curly "{}" bracks
user = {}  
user[:first] = "Papa" #associating the symbol :first to the string "Papa"  
user[:last] = "Jah" #associating the symbol :last to the string "Jah"  
#2. Use the hash rocket directly "=>"
user = { :first => "Papa", :last => "Jah"}  
#3. Use special Rails notation for hash assignments
user = { first: "Papa", last: "Jah" }*  

Using a hash you can efficiently store varying types of data to a unique person or ID. It’s important to note that order does not matter in a hash. If you have a data set that requires ordering then a better tool to use would be an array.

*The spaces between the curly brackets are not necessary but generally used by the rails community

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s