Array of Values
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 of mixed-type values.
Accessing individual values
The individual values in an array are accessed through an index. An index is an integer representing the position of an individual value in the array. We enclose the index in square brackets after the array variable name. The first value is at index 0
, and the index moves forward in the array by linear increments. Ruby also allows negative indexes. The last value is at index -1
, and the index moves backward in the array by linear decrements, as demonstrated in the following code:
a = [-5, 'Ruby', 3.8]print("\nArray items in the forward order: ")print("\nThe value at index 0: ", a[0])print("\nThe value at index 1: ", a[1])print("\nThe value at index 2: ", a[2])print("\nArray items in the backward order: ")print("\nThe value at index -1: ", a[-1])print("\nThe value at index -2: ", a[-2])print("\nThe value at index -3: ", a[-3])
The following figure illustrates the forward (non-negative) and backward (negative) index values used in the code above. The indexes, 0
and -3
, refer to the same value in the array. Similarly, 1
and -2
both refer to the value Ruby, and 2
and -1
both refer to the value 3.8
.
Slice the array
A slice is a subset of values from an array. We use the syntax, [i..f]
, to specify the initial and final index of the array to access as a slice. There are several ways to access a slice of an array.
- Use both values with
...
, as in[i...f]
, to access the slice from indexi
to indexf-1
. - Use both values with
..
, as in[i..f]
, to access the slice from indexi
to indexf
. - Use two values separated by
,
, as in[i, n]
, to access the slice ofn
characters starting from the indexi
.
Several other commonly used ways to access a subset of values from an array are shown in the program below:
letters = ['a','b','c','d','e','f','g','h','i']print("Array of letters: ")print(letters)# Slicing array using ".." rangeprint("\nSlices of an array: ","\n")print('Slice "[1..array.length]" from index 1 till the end',"\n")print(letters[1..letters.length],"\n")print('Slice "[-2..array.length]" from index -2 till the end',"\n")print(letters[-2..letters.length],"\n")
In the code above:
- The new item is the
.length()
function, which is used to get the length of the array. ..
is used to specify a range of indexes.- In
letters[1..letters.length]
andletters[-2..letters.length]
, we give the starting index, and the ending index is the length of theletters
array.
letters = ['a','b','c','d','e','f','g','h','i']print("Array of letters: ")print(letters)# Slicing array using "..." rangeprint("\nSlices of an array: ","\n")print('Slice "[1...]" from index 1 till the end',"\n")print(letters[1...],"\n")print('Slice "[-2...]" from index -2 till the end',"\n")print(letters[-2...],"\n")print('Slice "[...3]" from start of the array till before index 3',"\n")print(letters[...3],"\n")print('Slice "[...-3]" from start of the array till before index -3',"\n")print(letters[...-3],"\n")
In the code above:
...
is used to specify a range of indexes.- In
letters[...3]
andletters[...-3]
, we only give the ending index.
The following program demonstrates the use of both index ranges with (...
).
letters = ['a','b','c','d','e','f','g','h','i']print("Array of letters: ","\n")print(letters,"\n")# When starting or ending index is in rangeprint('Slice "[2...7]" from index 2 till before index 7',"\n")print(letters[2...7],"\n")print('Slice "[2...-4]" from index 2 till before index -4',"\n")print(letters[2...-4],"\n")print('Slice "[-4...-1]" from index -4 till before index -1',"\n")print(letters[-4...-1],"\n")print('Slice "[-6...8]" from index -6 till before index 8',"\n")print(letters[-6...8],"\n")
In the code above:
- In
letter [ 2 ... 7 ]
,letter [ 2 ... -4 ]
,letter [ -4 ... -1 ]
, andletter [ -6 ... 8 ]
, we give both the starting index and the ending index for each slice. These slices will contain the values starting at the first index and ending before the second index.
letters = ['a','b','c','d','e','f','g','h','i']print("Array of letters: ","\n")print(letters,"\n")# When starting or ending index is out of rangeprint('Slice "[7...2]" from index 7 till before index 2',"\n")print('no element in this wrongly ordered index values',"\n")print(letters[7...2],"\n")print('Slice "[-2...-4]" from index -2 till before index -4',"\n")print('no element in this wrongly ordered index values',"\n")print(letters[-2...-4],"\n")
In the code above:
- The last two examples,
letter [ 7 ... 2 ]
andletter [ -2 ... -4 ]
, demonstrate that when the starting index is larger than the ending index, then the result is an empty array.
Practice for array manipulation
The following are a few example programs to practice using arrays in Ruby. There are built-in operations for some tasks mentioned below. However, it’s good practice to write them from scratch.
By clicking the “Show Solution” button, you can find a program that solves the respective problem. You can copy and paste the given solution into the code widget to make sure the output of your solution matches the given solution. There may be several ways of writing correct solutions in programming.
Sum of array elements
Write a program that shows the sum of elements in an array.
Sample input
[10,20,30,40,50]
Sample output
150
# Write your program here.
Sum adjacent values
Write a program that displays the sum of every two adjacent values in an array.
Sample input
[10,20,30,40,50]
Sample output
[30, 50, 70, 90, 50]
# Write your program here.
Construct a decimal number
Write a program that converts an array of single-digit values into a single decimal number. The length of the array is restricted to five values.
Sample input
[1,2,3,4,5]
Sample output
12345
# Write your program here.
Palindrome test
Write a program that checks if an array is a palindrome. The length of the array is restricted to five elements.
Sample input 1
['ab','cd','ef','cd','ab']
Sample output 1
['ab', 'cd', 'ef', 'cd', 'ab'] is a palindrome
Sample input 2
['a','c','e','d','a']
Sample output 2
['a', 'c', 'e', 'd', 'a'] is NOT a palindrome
# Write your program here.
Reverse an array
Write a program that reverses the order of elements in an array. The length of the array is restricted to eight values.
Sample input
v = [1, 2, 4, 8, 7, 6, 5, 3]
Sample output
Original array: [1, 2, 4, 8, 7, 6, 5, 3]
Reversed array: [3, 5, 6, 7, 8, 4, 2, 1]
# Write your program here.