Day 19 of #100daysofCode - Hashes 101

sincerelybrittany profile image Brittany ・2 min read

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)}

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 


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)}

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.


Song of the day

Posted on by:

sincerelybrittany profile



Developer | Software Engineer 👩🏾‍💻 | Determined | Music & Dance | Completed #100DaysofCode | #WomenWhoCode


markdown guide