Hashes

What are hashes? 

  • Like an array, but the index can be anything:
  • integers, strings, symbols, or even objects
  • Instead of array[1] = "fun" we have hash["ruby"] = "fun"
  • Example:
  • StudentNumbers = { "WDI4" => 9, "WDI5" => 15 }

An analogy

Array 

Hash

Grocery shopping

Creating hashes:

code-along

Why are they cool? 

  • Human readable: animals[1] vs animals["cats"]
  • One of the most common data structures you'll encounter
  • Key-value logic is everywhere, even in NoSQL databases

When will you use them?

  • Does your data need a label?
  • Do you need fast lookups? 
  • Are you working with JSON? 
  • require 'json' then hash.to_json

Using hashes:

code-along

Further reading

Hashes

By Tom Dane

Hashes

  • 453