Lesson 4 of 10
Arrays and their methods
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
Add, remove and sort
Explanation
An array is an ordered list of values, like scores = [72, 95, 64]. You read each item by its position, counting from zero, so scores[0] is the first and scores[-1] is the last, and those two also have clearer names: first and last. include?(x) asks whether a value is there, and index(x) returns the position of its first occurrence, or nil if it isn't there.
Some operations change the array itself: << adds an item at the end, push does the same but accepts more than one item, and pop removes the last item and returns it, so you can keep what you removed if you need it.
sort and uniq, on the other hand, return a new array and leave the original alone. If you write scores.sort on a line by itself, the values get sorted and then the result is lost, so store it in a variable. You can also chain the two methods, like scores.uniq.sort.
Your task
Two late scores have come in: add 81 with <<, then 47 with push. Then it turns out the last score was entered by mistake, so remove it with pop and store it in wrong. After that, build ranked from the scores with no duplicates, sorted in ascending order, and take lowest and highest from it with first and last. Set top_at to the position of the first 95 in scores, and set has_full to whether scores contains a 100.
Checks
6 checks- scores is correct after adding and removing, and keeps its original order
- wrong is the removed score, 47
- ranked has no duplicates and is sorted in ascending order
- lowest and highest are the lowest and highest scores
- top_at is the position of the first 95, counting from zero
- has_full is false because there's no score of 100