Hashes

ahuynh3a

Annie Huynh

Posted on November 28, 2023

Hashes

Definition:
A collection of key-value pairs. They are like dictionaries.

Hash syntax looks like this:

hash = {
  key1 => value1,
  key2 => value2,
  key3 => value3
}
Enter fullscreen mode Exit fullscreen mode

Values are assigned to keys using =>. Any ruby object can be a key or value.

  • Note: This is the literal notation. This is because you literally describe what you want in the hash: you give it a name and you set it equal to one or more key => value pairs inside curly braces.

Using Hash.new

Another way to create a hash is using Hash.new (Hash must be capitalized) like this:

my_hash = Hash.new

Enter fullscreen mode Exit fullscreen mode

This is the same as my_hash = {}

Setting a variable equal to Hash.new creates a new, empty hash.

Adding to a Hash

Three ways:

  1. Literal notation: simply add a new key-value pair directly between the curly braces

  2. Bracket notation: Hash[key] = value

For example:

pets = Hash.new
pets["Stevie"] = "cat"
pets["Lucky"] = "dog"
pets["Sam"] = "snake"
Enter fullscreen mode Exit fullscreen mode
  1. Using the .store method
students = Hash.new
students.store(:name, "John Doe")
students.store(:age,22)
students.store(:grade,"A")

Enter fullscreen mode Exit fullscreen mode

Accessing Hash Values

Very similar to accessing values in an array.

To access the value, access the key first using brackets:

pets = {
  "Stevie" => "cat",
  "Bowser" => "hamster",
  "Kevin Sorbo" => "fish"}

puts pets["Stevie"]
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ahuynh3a
Annie Huynh

Posted on November 28, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related