Arrays vs Hashes

Here is a quick rundown on the difference between arrays and hashes! This is a pretty basic overview.

Arrays

The array is basically a list of values or items separated by commas. (CSV! My favorite data format!) Arrays are pretty straightforward.

Array = [ “a cool string”, 5, “another cool string”, “word”, 19983578923485]

Key facts about arrays:

  • Denoted by square brackets [  ]
  • Values are separated by commas [ value1, value2]
  • Order matters!
  • Access individual items via their index. ex: Array[0] gives the first item in the array.

Hashes

Hashes are cool! (And not just because they wear bowties.) A hash looks a little bit like an array, but with different brackets and each position in a hash is made up of a pair of things instead of a single item. The left side of the pair is called the key and the right side is the value. As in, it is KEY to remember the KEY otherwise you will not be able to access the VALUE. Also, the order of items in the array does not matter, because instead of looking up things by their position or index, we look up values in an array by their key.

Hash = { “pumpkin pie” => “is delicious”, 42 => “life the universe and everything”, :dog => “cute!”, nailpolish: “green” }

Key facts about hashes:

  • Denoted by curly brackets { }
  • Key/values pairs are separated by commas { hash1: key1, hash2: key2 } (new syntax) OR { hash1 => key1, hash2 => key2 } (old syntax)
  • Order doesn’t matter!
  • Access individual items via their key. ex: Hash[“key”]
  • That little equals-greater-than symbol that ties the key and value together? It is called a hash rocket! => => =>
  • Can contain symbols as keys! Those are the guys that are either start (or sometimes end with) a colon.

Leave a Reply

Your email address will not be published. Required fields are marked *