Hashes

Rumiko Acopa
2 min readJun 28, 2021

My weekly coding…

This week was busy but I was able to get in some coding. My focus was on hashes.

  • Figure out how to practice your coding in ruby playground.rb
  • Figure out how to use Repl.it to practice your coding skills as well.
  • Practice, Practice and Practice some more!

“Hashing Around”

Start by creating a hash.

Photo by Nicole Wolf on Unsplash
{}hash_name = {'name' => 'Logan', 'favorite color' => 'Yellow'}

To access the value of the hash and figure out what is the name.

hash_name["name"]

Creating a |key, value| pair

Photo by Silas Köhler on Unsplash
new_hash = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6}

However, doing this will create symbols a, b, c , d, e, and f (not strings) as keys

To get the value for key e above you can do this:

new_hash[:e]

In order to add a |key, value| pair to the hash above:

new_hash[:b] = 9new_hash[:name] = "Professor X "

If you would like to delete a |key, value| pair simply delete the key:

new_hash.delete(:b)

You may want to list the keys in a hash, followed by values of the hash:

new_hash.keys
new_hash.values
Photo by Ricardo Gomez Angel on Unsplash

Iterating Through A Hash

Iterate through a hash

  • use .each method
  • print out the value

new_hash.each { |somekey, somevalue| puts somevalue }

Iterate through a hash

  • use .each method
  • print out both key and value

new_hash.each { |somekey, somevalue| puts "The key is #{somekey} and the value is #{somevalue}" }

Iterate and delete an item & a condition (in the condition below if the value is less than 3:

new_hash.each { |k, v| new_hash.delete(k) if v < 3 }

Learn how to find the methods

rubyonrails.org is a great way to look up methods to use. One method is the select method. This example method displays items only if value of the item is even

new_hash.select { |k, v| v.even? }

Happy Coding!

#YourCodingEsty

--

--