A.9 Hash
list of objects represented with curly brackets, {}. Unlike Arrays, each cell is not automatically numbered but given a label by us.
A.9.1 Interlude: Symbol
Symbols are a sequence of characters and are used to to label something internally in the code. They are created by starting them off with a colon and follow the same naming conventions as variables, :hello
.
:hello.class # => Symbol
A.9.3 .store
Hash#store(Object, Object) ⇒ Object
Adds elements to a Hash by taking two arguments, a label (or key) and a piece of data (or value).
This method returns the Object
that was stored.
The key
can be any type, although is usually a Symbol
. The value can also be of any type.
:first_name, "Raghu")
person1.store(:last_name, "Betina")
person1.store(:role, "Instructor")
person1.store(# => person1 = {:first_name=>"Raghu", :last_name=>"Betina", :role=>"Instructor"}
or we can fill up a hash by typing in the hash literal
person2 = { :first_name => "Jocelyn", :last_name => "Williams", :role => "Student" }
Note:
1. Ruby represents each key/value pair by separating them with a =>
, known as a “hash rocket.”
2. If the value associated with a key already exists when you try to .store
something under it, its value will be replaced.
A.9.4 .fetch
Hash#fetch(Object) ⇒ Object
or
Hash#fetch(Object, Object) ⇒ Object
Both .fetch
and .[]
can be used to retrieves the data held by a key.
person1.fetch(:last_name)# => "Betina"
person2.[:last_name] # => "Williams"
If .fetch
is given key that is not present in the hash, it will throw an error. But .[]
is given key that is not present in the hash, it returns nil
.
Fallback: pass in a second default argument that .fetch
will return if the key is not present in the hash.
person1.fetch(:middle_name, "None provided") # => "None provided"