DEV Community

Adriana
Adriana

Posted on

Ruby Hash Notes

.store method adds elements to a hash (as opposed to .push with arrays)
-.store takes two arguments, one label and one value
i.e person1.store(:first_name, “Adriana”)
The output will reflect as such: first_name => Adriana

Store Shorthand
Input:
person1 = Hash.new
person1[:first_name] = “Adriana”
person1[:last_name] = “Lopez”
person1[:role] = “Student”

pp person1

Output:
{:first_name=>”Adriana”, :last_name=>”Lopez”, :role=>”Student”}

.fetch will retrieve just the value within the dataset
Input:
pp person1.fetch(:first_name)
Output: “Adriana”

Fetch fallback
To ensure the program doesn’t crash when it tries to retrieve a value that is not there, we can make placeholder values
Input:
person1.store(:first_name, “Adriana”)
pp person1.fetch(:first_name, “None provided”)
pp person1.fetch(:middle_name, “None provided”)

Output:
“Adriana”
“None provided”

Fetch Shorthand
Input:
person1.store(:first_name, “Adriana”)
pp person1.fetch(:first_name)
pp person1[:first_name]

Output:
“Adriana”
“Adriana”

If there is no value when using the [] Notation, the output will result in “Nil”. If there is no value with the standard notation, the output will result in “an error”

Hash Literal Notation:
Input:
person1 = { :first_name => “Adriana”, :last_name => “Lopez” }
pp person1

Output:
{:first_name=>”Adriana”, :last_name=>”Lopez”}

.keys method is used to show all the keys present in a hash. This is returned within an array
Input:
h { “a” => 1, “b” => 2, “c” => 3 }
pp h.keys
pp h.fetch(“b”)

Output:
[“a”, “b”, “c”]
2

.key method with arguments is like .fetch in reverse, it searches for the key of a given value
Input:
h { “a” => 1, “b” => 2, “c” => 3 }
pp h.key(2)
pp h.key(5)

Output:
“b”
nil

Values within Values
Input:
dictionary = {
:colors => [“red”, “green”, “blue”]
:person => {
:name => “Adriana Lopez”,
:age => 22
}
}

colors_array = dictionary.fetch(:colors)
pp colors_array
pp colors_array.at(1)
pp person_hash = dictionary.fetch(:person)
pp person_hash.fetch(:age)

Output:
[“red”, “green”, “blue”]
“green”
{ :name => “Adriana Lopez”, :age => 22}
22

Top comments (0)