Ruby collections: arrays
Ruby arrays hold an ordered list of values behind one name. This course covers creating arrays with square brackets, reading elements by zero-based and negative indices, and using first, last, length and size. The methods push, <<, pop, unshift and shift change an array in place. The methods include?, index and empty? answer common questions, and slicing works with [start, length] or a range. It also covers sort, reverse and their bang versions, cleaning with uniq, compact and flatten, and combining arrays with +, -, & and |.
What you'll learn
- ✓Creating arrays and reading elements with zero-based and negative indices
- ✓Adding and removing elements at both ends with push, <<, pop, unshift and shift
- ✓Searching arrays with include?, index and empty?
- ✓Slicing with [start, length], ranges, first(n) and last(n)
- ✓Sorting and reversing, and the difference between sort and sort!
- ✓Cleaning and combining arrays with uniq, compact, flatten, +, -, & and |
Creating and accessing arrays
Every value so far, a number, a string or a boolean, lived alone in its own variable. An array holds an ordered list of values behind one name.
Read the full lesson free →Curriculum
7 lessonsCreating and accessing arrays
Creating arrays with square brackets, reading elements by zero-based and negative indices, and using first, last, length and size.
Adding and removing elements
Adding and removing elements at both ends with push, <<, pop, unshift and shift, all of which mutate the array.
Searching and checking arrays
Checking arrays with include?, index and empty?, and using them inside if and unless guard clauses.
Slicing arrays
Reading several elements at once with [start, length], inclusive and exclusive ranges, negative indices, and first(n) and last(n).
Sorting and reversing
Sorting and reversing with sort and reverse, their mutating bang versions, and the error from incomparable element types.
Combining and cleaning arrays
Cleaning arrays with uniq, compact and flatten, and combining two arrays with +, -, & and |.
Putting it together: a small challenge
A score summary method that chains compact, uniq and sort, followed by a challenge to write it yourself.