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

[AI 協作筆記] gRPC 傳輸優化:基於 Flattening 與 Bitset 的高效方案

[AI 協作筆記] gRPC 傳輸優化:基於 Flattening 與 Bitset 的高效方案 本篇文章記錄了在開發高效能資料庫中間件 (hypool) 時,針對 gRPC 傳輸效率與型別限制所採用的優化方案。該方案由 AI 協助提出,借鑑了資料庫底層儲存原理,解決了傳統 gRPC 在傳輸大量資料庫結果集時面臨的兩個主要挑戰。 1.…
Read More