Hashes–Another Data Structure!!! [Ruby Programming Language Notes]
Hashes! (Another data structure)
An array allows us to have a single variable, or location, to store & group a lot of data. (Allows for organization!)
An array was the first data structure we learned about.
[ ]–An array is made up of elements, organized by indices.
But sometimes we may need a different organization when building a program. That’s why we have HASHES!!!
A hash is made up of values stored by keys. (A key “unlocks” the corresponding value.)
{ }–curly braces are used to represent a hash in Ruby. (This can be assigned to a variable.)
In a hash, data comes in a pair, (a ‘key value’ pair).
- my_hash = { “name” => “Programming School”, “color” => “red”, “age” => 5 }
- In this line directly above, ‘my_hash‘ represents the “variable“, the “hash” is within the {}‘s, the set [“name“, “color“, “age“] are the “keys“, ‘=>‘ denotes a “rocket” symbol, and the set [“Programming School“, “red“, “5“] are the “values“.
- Similarly to arrays,
- my_hash[“key”] will return the “value”! (Similar to indexing [] into an array.)
- .length will return the number of ‘key-value’ pairs in the hash. So using the above example: ‘my_hash.length‘ would return ‘3’, for 3 pairs.
Hash Methods
*Many array methods can be used on hashes.
Other Methods:
- hash.length–return number of key-value pairs
- hash.has_key?(“keyword”)–returns a boolean (note the question mark); can be used to check for existence inside a hash.
- hash.has_value?(Value example)–returns a boolean (we know this b/c of the question mark).
- hash.keys–returns an array of the hashes keys.
- Can be used to index into like:
- hash.keys[index]
- …because ‘.keys‘ returns an array, (so we can ‘index’ into it!)
- Can be used to index into like:
Similarly, with:
- hash.values–returns an array of all the values;
As we get these data types we can use any other operations we want using previously learned info!
Why Hashes?/Use Cases
- Arrays are good to use in order to represent a collection of similar things. (i.e.–multiple things)
- Ex: animals = [“dog”, “cat”, “fish”, “bird”]
- Hashes are good to represent many facets, or characteristics of a single thing.
- Ex: person = { “name” => “Aaron”, “age” => 100, “location” => “NYC” }
Hash Enumerables
- .each–We can iterate thru a hash using the ‘.each‘ method. It passes each key & value to the block-parameter. (Gives us access to the key & also the value!)
- hash.each do |key, value|
- puts key
- puts value
- end
- hash.each do |key, value|
- each_key–iterate over just keys; passing keys;
- hash.each_key do |thing| #note–Remember that these parameter variables can be named anything! Use what names make sense.
- puts thing
- end
- hash.each_key do |thing| #note–Remember that these parameter variables can be named anything! Use what names make sense.
- each_value–iterate thru each value; passing the values to the block.
- hash.each_value do |val|
- puts val
- end
- hash.each_value do |val|
Assigning Key & Values
Adding Keys & Values to an Empty Hash
- my_hash = { } #empty hash
- my_hash [“key”] = 4 #create a “key” word and specify or assign it a value.
- puts my_hash
- This will return –> { “key” 4 }
Or we can make it dynamic by using variables:
- hash = { } #Empty hash created
- word = “this” #Variable created
- hash[word] = word.length #Keyword created & assigned to a value! ‘word.length’ will evaluate to a value.
- puts hash
- { “this” => 4 }
More Hash Properties
- A hashes default value is nil (if nothing is assigned).
- Ex:
- my_hash = { “a” => 28 }
- puts my_hash [“a”] will return 28.
- puts my_hash [“b”] will return nothing (blank) but it’s corresponding value is actually nil.
- Ex:
- We can initialize a hash with a different default value than nil.
- Ex: my_hash = Hash.new(0) #default value we want to assign.
- Ex: my_hash = Hash.new(“hello”) #now “hello” is the default value.
Counter Iterate
Let’s just change the variable name to counter.
Ex: counter = Hash.new(0)
If we do:
- str = “kitchen prep”
- str.each_char { |char| counter[char] += 1 }
- puts counter
- Output: { “k” => 1, “i” => 1, “t” => 1, “c” => 1, “h” => 1, “e” => 2, “n” => 1, ” ” => 1, “p” => 2, “r” => 1, }
- The code Hash.new() is the only way to initialize the default value of a hash.
- ex: count = Hash.new(0)
- –sets the default value to 0.
Sort by
my_hash.sort_by { |k, v| k }
‘Sort by‘ passes in a block of the key & the value. Then we specify which of these criteria we want to sort by, the k or the v.
*Ask yourself what data you have right now, & that will dictate what to do next.