Greatest class of all time
Arrayclass 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
length methods, which return the number of elements present in the array.
countalso takes in a single object argument and returns the count of the array for which elements equal to that object.
countalso 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.
indexmethod 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
flattenmethod 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.
flattenwill jump in to.
compactmethod returns a new array with all the
42in the one-dimensional representation of the array is
zipmethod 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 or a
joinis useful for joining all the array elements into a string. You can add a separator between by specifying it as a
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
unshifttakes 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.
U directive converts to UTF-8 characters. 177 and 8978 are code-points for the characters
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.