Greatest class of all time
Array
class in Ruby has over 100 public methods. We'll go through a bunch of these and move on to some real world applications in the penultimate sections.
Starting off with the method count
we used above.
count
used without any arguments acts like the size
or length
methods, which return the number of elements present in the array.
count
also takes in a single object argument and returns the count of the array for which elements equal to that object.
count
also takes in a block and returns the number of elements in the array for which the block results to true
. Find out the number of even numbers in this array.
index
method returns the index of the object specified. If a block is given it returns the index of the first element for which the block results to true
.
flatten
method returns a one-dimensional array representation of the array. It recursively picks out all elements from the inner-arrays and lays them out in the outermost array.
flatten
will jump in to.
compact
method returns a new array with all the nil
elements removed.
42
in the one-dimensional representation of the array is 5
.
zip
method expects variable number of arguments and returns an array of arrays that contain corresponding elements from each array. That is, an element-wise merge with the original array.
If the elements of the array arguments passed to zip
aren't equal to the array it's being called on, then it assigns nil
to the faulty combination in the sequence.
slice
is same as using the literal []
form for extracting subarrays.
It accepts an index, like array[2]
or a Range
, like array[2..7]
join
is useful for joining all the array elements into a string. You can add a separator between by specifying it as a String
argument.
If you notice, join
only applies the separator between two elements, hence sparing the last element. This makes join
really convenient for sanitizing information to be displayed.
Write a method that takes an array argument, slices off the last two elements and returns a string of those two elements separated by "|"
shift
removes the first element of the array and returns it. Shifts the rest of the array towards left, such that the second element becomes the first element, the third element becomes the second one and so on.
You can also specify an optional argument -- shift(n)
that will remove and return an array of the first n
elements.
unshift
takes a variable number of arguments and adds them to the beginning of the array.
pack
returns a packed string of the array elements converted into appropriate binary sequences. There are quite a few directives you can specify for this, use this table for reference.
The U
directive converts to UTF-8 characters. 177 and 8978 are code-points for the characters ±
and ?
respectively.
The directives depends on the number of array elements. We specify U
twice because we have two elements. You can use *
to collect all the elements.