Day 19 of #100daysofCode - Hashes 101
Brittany
Posted on June 19, 2020
During my project review, I was asked to iterate over a hash and sanitize the params inside. I am used to iterating over arrays and had forgotten how to iterate over a hash. Along came GOOGLE. I quickly googled, how do you iterate over a hash?
I was only allowed to use the Ruby docs and found this Ruby-Doc
I realized iterating over a hash is relatively similar to an array, so I attempted to use a .map
method. It did not take long for me to realize that using the the .map
method on a hash returns an array. WHO KNEW? So, I quickly realized that it was necessary to use the .each
method. The docs revealed that .each
on a hash should be used like this:
h.each {|key, value| puts "#{key} is #{value}" }
Pretty simple. I took this and created a santize_hash
in my helpers and copied the code below.
def sanitize_hash(h)
h.each {|key, value| [key] = sanitize(value)}
end
However, this method was not going to work just yet. I had to create an empty hash and place the keys and values into that hash. I had to think back to the beginning, when I first started studying hashes and arrays.
Hashes are essentially dictionaries. They are similar to arrays except they use objects as an index instead of numbers.
There are two ways to create a hash:
hash = Hash.new
OR
hash = {}
In order to complete my sanitize_hash
method I adding an empty hash before iterating. Upon iteration, I added the key to the empty hash with the sanitized value, like this:
def sanitize_hash(h)
hash = {}
h.each {|key, value| hash[key] = sanitize(value)}
hash
end
I have discovered how important it is to have an understanding of hashes and plan to expand my knowledge on hashes in the near future.
JUNETEENTH
Song of the day
Posted on June 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.