Lining 'em up
You've already completed the basic introduction to Arrays and are ready to delve deeper. This chapter will cover Ruby's Array
in some detail, and demonstrate advanced techniques around the creation and manipulation of arrays.
You've already completed the basic introduction to Arrays and are ready to delve deeper. This chapter will cover Ruby's Array
in some detail, and demonstrate advanced techniques around the creation and manipulation of arrays.
This is destructuring. We've broken down the array and assigned its values to zen
and life
.
This is equivalent to using the bracket form or the at
method to extract values. giving you nice a shorthand for doing a sequential breakdown of an array.
n-element
arrays within an array. That is, each element of the array is also an array of n
items.
zen
and john
expectedly select the first two inner-arrays.
It's also possible to write a function and use it in a way as to simulate returning multiple values from it. In practice, this is rarely necessary. But it's fun to know you can!
All this is pretty neat. What is even nicer is that you can use this inside blocks.
Finish this method to return an array. The method accepts only a two-dimensional array. The elements of the array that this method returns are the sums of the first two elements of each inner-array of the two-dimensional array that is passed in.
more
is ignored and simply assigned nil
because we're out of elements in the array.
Ruby has a more dedicated way of destructuring using the splat (*) operator.
This is different from our regular way of destructuring by assignment as instead of just splitting the array up into the number of variables present on the left hand side, we're splitting the array up by the number of variables and slurping the rest of the array into the second variable with the splat (*).
This example should make this more clear.
initial
here only slurps the elements before 44
. This is because we have two variables and last
takes away the final value.
What if we add another variable into this?
As expected, initial
only slurps [42]
from the array. The last two values are assigned to the last two variables.
Modify this expression to slurp the middle portion of this array using a middle
variable.
You can however only splat the last parameter of a method.
Now write an exercise to calculate the median from a set of numbers. Assuming that median
method takes in the list as arguments passed in.
Range
, String
and convert them into Array
objects.
a
is the first element and b
is an array containing the rest of the elements.
Hash
is often created using the array form that takes in even number of arguments as key-value pairs, or directly, a two-dimensional array with paired arrays.
Array
class provides in the next lesson.