Intro to Hashes Lab
Learning Goals
- Build simple hashes.
- Access and modify data stored in a hash.
- Add new data to a hash.
Introduction
Its time to practice what we've learned about Ruby hashes. In this lab, your
task is to implement a set of methods. Each method will require you to complete
some basic hash creation and modification. Use learn
and follow the test
suite messages as you work through your solution.
Instructions
-
Create a method called
#new_hash
that creates and returns a new, empty hash. -
Create a method called
#my_hash
that returns a valid hash. This hash should have at least one key/value pair of your choice. -
Create a method called
#actor
that returns a hash. This hash should have a key that is a symbol:name
and whose value is a string,'Dwayne The Rock Johnson'
. -
Create a method called
#read_from_hash
that takes in two parameters. The first is a hash, and the second is a key. Use the provided key and bracket notation to access and return the corresponding value. For instance, if the following hash was passed in:
{
name: "Sam",
age: 31
}
...and the key provided was :age
, this method should return 31
.
-
Create a method called
#id_generator
that creates and returns a hash with one key/value pair. The key should be a symbol,:id
. For the value, generate a random number value using Ruby's built inrand
method. -
Create a method called
#my_hash_creator
that takes in two parameters. In this method, create and return a hash with one key/value pair, using the first parameter as the key, and the second parameter as the value. -
Create a method called
#update_counting_hash
that takes in two parameters. The first parameter is a hash, and the second is a key. The hash provided will have any number of keys, but all values will be integers. The#update_hash
method should do one of two things: increment an existing value based on the provided key parameter, or create a new key/value pair using the provided key, setting the value to1
. So, for example, if we had the following hash:
{
:apples => 3
}
..and a provided key, :apples
, #update_hash
should return an updated
hash:
{
:apples => 4
}
However, if the hash was given a key that doesn't exist, like :oranges
, it
should return:
{
:apples => 3,
:oranges => 1
}
Conclusion
Hashes are a key data type that we will end up using frequently. Now that you've grasped the basics of creating, reading and updating hashes, we can explore some examples of more complicated hashes!