Hashes 'N Arrays
January 23, 2016
Okay so how to explain hashes and arrays. Well, first off, hash does not mean ... y'know... hash.
Mmmmm yum.
I like to think of hash as a group of information and an array as a list of stuff. Just stuff like words, sentences, numbers, arrays, hashes, more sentences. That kind of thing. No big.
Hash.new = {"dog"=>"Spot", "cat"=>"Duchess", "person"=>"Gertrude"}
Array.new = ["YOLO", 32.01, "I like Ruby", [1,2,3,4]]
Arrays are best suited for list things like a set of numbers or employee names. But the company wants information on an employee? A hash comes in handy here!
Here we have our list of employee numbers: employee_numbers.new = [...101, 102, 105,...]
We use a hash to store information about an employee number: emp_num102.new = {"first_name"=>"Gertrude", "last_name"=>"Smith", "address"=>"3214 Fashion Avenue, Chicago, IL 63546"}
If you're not sure if to use an array or hash, think of it this way: Is your list of items simple (i.e. milk, bread, cookies)? Use an Array! Or is it specific (i.e. low-fat Uncle Bob's dairy farm milk, white wonderbread, Chips Ahoy! chewy chocolate chip cookies)? Use a hash!