Sometimes it takes a bit of repetition for a concept to click. Coding is like any new skill you might pick up -- the more you do it, the better you get at it. Last unit we covered arrays and hashes. Let's review what we learned.
Lesson Plan
Difference between an array and a hash -
Think of an array as a list of items. We access information in an array from an index, starting with 0.
A hash is more specific way of labeling information. A hash is made up of key-value pairs. Keys have to be unique. Access information in a hash through the key.
Syntax for arrays and hashes
*Array:
snax=["chips","oreos","celery"]snax[0]#returns "chips"snax.delete("celery")#removes celerysnax << "popcorn"#adds popcorn to the end of the array)]snax.push("trail mix")#adds trail mix to the end of the arraysnax.last#returns trail mixsnax.first#returns chipssnax[3]="Cotton Candy"#replaces trail mix with cotton candy
Hashes
todo={:homework=>"Algebra problems",:chores=>"make my bed",:shopping=>"buy new shoes"}todo[:homework]#returns Algebra Problemstodo.delete(:homework)#removes that key-value pair from the hashtodo[:travel]="Go to Spain"#adds that key value pair to the hashtodo[:chores]="laundry"#changes the value of the :chores key to laundry
Iterating over arrays and hashes
Arrays:
snax=["chips","oreos","celery"]snax.eachdo |snack|
"I love #{snack}"end
Hashes:
todo={:homework=>"Algebra problems",:chores=>"make my bed",:shopping=>"buy new shoes"}todo.eachdo |category,task|
"I have so much to do! #{category}: #{task}"endtodo.each_keydo |category|
"I have to do #{category}"endtodo.each_valuedo |task|
"I have to #{task}!!!"end
Create array with the different ages in the class. Then calculate:
The sum of all the ages
total=0ages=[15,16,17,19]ages.eachdo |age|
total += ageendtotal
The average age
ages=[15,16,17,19]sum=0.0ages.eachdo |age|
sum += ageendputssum/ages.length