Hashes

hashes

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

Hash syntax looks like this:

hash = {
  key1 => value1,
  key2 => value2,
  key3 => value3
}

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

This is the same as my_hash = {}

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

Adding to a Hash

Two 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"

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"]
Total
0
Shares
Leave a Reply

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

Previous Post
women-in-ml-symposium-2023:-meet-the-presenters

Women in ML Symposium 2023: Meet the presenters

Next Post
flutter:-seamless-header-navigation-from-appbar

Flutter: Seamless Header Navigation from AppBar

Related Posts