Ruby Hashes

Hashes in Ruby are a helpful way to organize information. As can be seen in the screenshot below, I've created a new hash, named it example, and given it a couple keys and values to start. To create your own hash, just pick the name you want it to be called and set that equal to Hash.new. Since Ruby is case-sensitive, it's important to remember to capitalize Hash.new. To set keys and values, use the format: hashname["key"] = "value". In my example hash, I've created the keys "cold" and "hot" and given them values of "pluto" and "sun" respectively.

Screen shot 2013-11-15 at 8.47.33 AM

Next, you can get input from the user and add it to the hash as  a key or a value.

Screen shot 2013-11-15 at 8.53.04 AM

Set a variable (I've used input) equal to gets.chomp. If you want the user to keep putting in new input, you'll have to put this multiple times, otherwise your variable will stay as whatever it was first set as. The below screenshot is what happens when I run this program and put hi as the input for the value. It doesn't have spaces, but you can see at the beginning of the printed hash that hi has been integrated into the hash.

Screen shot 2013-11-15 at 8.51.44 AM

Some methods that are useful when dealing with hashes are .has_key? and .has_value?. They are formatted in Ruby like this: hashname.has_key?["key"] and hashname.has_value?["value"]

Screen shot 2013-11-18 at 9.38.54 AM

 

You don't need to use the if statements with them, but I've put them in so that when I run the program...

Screen shot 2013-11-18 at 9.42.56 AM

You can see that the methods work. These are just a few things you can do with hashes in Ruby. With enough practice and use, they can become one of the most helpful information organizing tools in your Ruby toolbox.

Comments