Learn and practice manipulating arrays of values in Ruby
What is an array
In Ruby, an array is a
collection of values stored as a single variable. For example, ["apple","mango","banana"]
is an array of strings. It is stored as a variable just like any other data type.
The following program demonstrates how to create an array of string values:
arrayOfFruits = ["apple","mango","banana"] # Creating an array of stringsprint(arrayOfFruits,"\n")
In the code above:
- We use a variable,
arrayOfFruits
, to assign the comma-separated values enclosed in square brackets. - We call the
arrayOfFruits
variable an array.
The following program demonstrates the various types of arrays in Ruby:
array0 = []print("Empty array: ")print(array0)array1 = [100]print("\nSingle-valued array: ")print(array1)array2 = [7, 7, 4, 4, 3, 3, 3, 6, 5]print("\nArray having duplicate Numbers: ")print(array2)array3 = [50, 'Learn', 10, 'To', 2.5, -1, 'Code']print("\nArray with the use of mixed values: ")print(array3)
Hint: We use
\n
with the print statements to display an extra line.
There are a few new things we have to understand in the code above.
-
The
array0
,array1
,array2
,array3
,array4
, andarray5
variables store array values. -
An array that has no values is an empty or a blank array (
array0
). -
An array can have only one value (
array1
). -
The variable
array2
holds an array of integers. The array may have duplicate values. -
The variable
array3
holds an array ...