Working with Arrays (1)
In order to do these exercises you should have read at least the chapter about [built_in_classes/arrays.html].
Make sure you have your text editor and terminal open, and you have navigated
to your exercises directory in the terminal. E.g.
In the Array
[1, 2, 3, 4, 5], what’s the index of the number
irb, how can you ask the Array, and check if your previous answer was correct?
irb, how can you ask the Array for the number of elements it contains?
Create a new, empty file. Save it as
arrays_1-1.rb. Fill in the following
numbers = [1, 2, 3, 4, 5, 6] # your code goes here
… so that, when you run your code (run
ruby arrays_1-1.rb), you get the
Copy your file to a new file:
cp arrays_1-1.rb arrays_1-2.rb, then open this
Add another line before the line that you just added, so that, when you run your code, you get the following output:
Make a new file
arrays_1-3.rb, and fill in the following line:
numbers = [1, 2, 3, 4, 5, 6] # your code goes here p numbers
… so that you get the following output:
[2, 4, 6]
You know how to get the individual numbers. And you know that you can list things separated by comma, and enclosed with square brackets in order to get a new Array. Try combining this, and “listing” the code that gets a number from the array.
Again, copy your last file to a new file:
cp arrays_1-3.rb arrays_1-4.rb,
then open this new file.
Now add another line after the one that you just added (i.e. before you
finally output the array using
Try to figure out how to transform your Array so you get the following output:
[6, 4, 2]
Before you do anything else, try describing the problem in English. What verb do you use to describe this transformation?
Look through the methods listed on the left side of the documentation for Arrays. to see if any of these describes what you’re looking for.