RubyKin

Practice

Arrays

1) Put the following kids in an array. Joe, Sally, Tom, Mary, Doug. Now sort them alphabetically using a standard Ruby method. What's the resulting array?

2) With your kid_array from question 1, separate the boys and girls into their own arrays. Then put your two new arrays into one array called "group". What is the least amount of lines required to write this code?

3) Now you should have one "group" array with two arrays nested inside. How might we reverse the order of each array? Hint: Ruby methods tend to be named by what they do.

4) Our class group has added one student, Tiffany. Add her to the girls list in our group array. What does our array look like now?

5) Imagine our list of boys and girls is much larger than just three. If each class can only have an equal number of boys and girls, how might a teacher ensure her lists are equal? Hint: You can use the count method to count the number of elements in an array.

Hashes

1) Create a hash for the Wizard’s magic bag. Inside the bag, we’ll put 3 frogs, 5 herbs, and 10 scrolls. Assign the hash to the variable "bag". What does your hash look like?

2) Remember, hashes consist of key value pairs of any data, not just numbers. Let’s add a wizard’s spell and its result (which the wizard can never seem to remember). Add a spell to our wizard’s bag with the key: "shazam" and the value "turns subject into a frog". Now what's in our bag?

3) Our wizard has a change of heart and decides he never wants to turn anyone into a frog. How can we remove the spell "shazam" from our wizard bag?

4) Our wizard has recently acquired 3 different types of potions. 4 orange potions, 5 blue potions and 7 red potions. How might we add another hash of potions to our bag?

Hint: remember that we can have collections within a collection.

5) Now that our bag has four keys (frogs, herbs, scrolls and potions), we can use these keys to access our data. In order to make a new spell, our wizard needs 2 frogs, 3 herbs, 1 scroll and 2 blue potions. How can we remove these items from our hash?

Hint: We can set the value of a key item to itself, minus how many items removed.