Last active
August 1, 2018 18:45
-
-
Save sheland/7a18a13b6d156e8efba03db5e4699e8c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Day 6 Exercises | |
#Updated 7/30/18 | |
#1 | |
#Ask the user to enter the names, ages, and favorite colors of their closest friends | |
#(you may not assume that the user's close friends all have unique names). | |
#Output the total number of close friends under 18, followed by their names. | |
#Output the number of unique favorite colors, and then list them | |
friends = [] | |
under_age = [] | |
colors = [] | |
puts "Welcome to Hash Fun!" | |
puts "You'll be entering your friend's name, age and favorite color" | |
puts "how many friends do you have?" | |
friend = gets.chomp.to_i | |
friend.times do #x(based on user input) runs a times loop | |
friends_hash = {} #every time the loop run a friends_hash is created | |
#inputs friend's names | |
puts "What's your friend's name?" | |
friend_name = gets.chomp | |
friends_hash["name"] = friend_name | |
#inputs friend's ages | |
puts "What's your friend's age?" | |
age = gets.chomp.to_i | |
friends_hash["age"] = age | |
#calulates underaged friends | |
if age < 18 | |
under_age << friend_name | |
end | |
#inputs friend's color | |
puts "What's your friend's favorite color?" | |
color = gets.chomp | |
friends_hash["color"] | |
colors << color | |
#displays name, age, color | |
print "You have #{under_age.count} friends that's younger than 18, #{under_age} years old" | |
puts " Your friend's favorite colors are #{colors.uniq}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice work! Just a few comments for further improvement:
friends_hash["color"]
Nothing gets assigned tofriends_hash["color"]
.friends_hash[:color]
rather thanfriends_hash["color"]
Applying the above comments, here's what your code will look like:
Can you see how fixing the indentation makes the code easier to read and hence makes i easier to spot error like the summary display should be outside the loop?
Finally, for additional practice, try having two more separate loops. The first loop just takes in user input and saves it in the array of hashes. The second loop saves all the colors from the hash into a separate array of colors and the third loop examines each of the ages in the array of hashes and creates the under_age array.