ruby · level 1 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Every item has a numbered spot, starting at 0.
Each item sits at a numbered position called its . Ruby starts counting at 0, so the first item is fruit[0]. Count back from the end with minus numbers: fruit[-1] is the last item.
Put a new value at an index to replace that item: fruit[1] = "pear". To a new item onto the end, use << or .push.
Ask for an index with no item there, and Ruby hands back , its word for nothing at all. puts nil shows an empty line.
fruit = ["apple", "banana", "cherry"]
puts fruit[0]
puts fruit[-1]
fruit[1] = "pear"
fruit << "lemon"
p fruit fruit << "lemon" and fruit.push("lemon") do the same job.
guess first
Which colour is at index 1?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
colours = ["red", "green", "blue"]
puts colours[1]
your turn
Your turn. Run a pet shop.
In the first blank, type a pet to add to the end. In the second, type a new pet to take the place of the cat. Then press run.
fix it
This should show the last fruit, but shows nothing. Fix it!
- Nothing shows. Which index does the last item really have?
- Indexes start at 0, so three items sit at 0, 1 and 2. Index 3 has nothing, so you get
nil. - Change fruit[3] to fruit[2], or to fruit[-1], then press run.
nailed it
you can reach any item you like. :D
- The first item is at index 0. The last is at -1.
- Replace an item with
fruit[1] = "pear". - Add to the end with
<<or.push.
new words in your collection
- index
- push
- nil
This lesson isn’t saved. A free account remembers every lesson you finish.