C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
First element: The first element in an array is located at index 0, not 1. This is standard for most programming languages.
Ruby program that uses array
# An array of integers.
values = Array[10, 20, 30, 40]
# Modify the first element.
values[0] = 100
# Display the array.
puts values
Output
100
20
30
40
Warning: In a zero-element array, first and last return nil. So we must check the result if our array may be empty.
Info: The first array element is located at the index 0. And the last is located at the position equal to length minus one.
Ruby program that uses first, last
elements = ["ruby", "diamond", "gold"]
# First is the 0 index.
puts elements.first
puts elements[0]
# Last index is length minus one.
puts elements.last
puts elements[elements.length - 1]
Output
ruby
ruby
gold
gold
And: We add the string "tree" and then "grass" to the array. The first element is "tree." The last is "grass."
Ruby program that uses push
# Create an empty array.
values = Array[]
# Push two elements.
values.push("tree")
values.push("grass")
# Print elements.
print "First: ", values.first, "\n"
print "Last: ", values.last, "\n"
Output
First: tree
Last: grass
Ruby program that uses append operator
items = Array[]
# Append two strings, one after another.
items << "cat" << "dog"
# Append another element.
items << "bird"
p items
Output
["cat", "dog", "bird"]
Delete_at: With delete_at(), we remove an element by specifying its index. No search is required.
Delete: With delete(), we remove the first element of the specified value. We remove the "lime" element without knowing its index.
Ruby program that deletes elements
# Citrus fruits.
arr = Array["orange", "lemon", "lime"]
# Delete element at index 1.
arr.delete_at(1)
puts "Fruit:", arr
# Delete element with value of "lime".
arr.delete("lime")
puts "Fruit:", arr
Output
Fruit:
orange
lime
Fruit:
orange
Block: The block must be surrounded by curly brackets. In the block, we supply a name for our element variable.
Here: I use "e." Another name like "x" could instead be used. The expression deletes all elements with values >= 40.
Ruby program that uses delete_if
# An array of integers.
numbers = [10, 20, 30, 40, 50]
# Delete numbers greater than or equal to 40.
numbers.delete_if {|e| e >= 40}
puts numbers
Output
10
20
30
Here: We create an array of three elements. We then pop it three times, yielding an empty array.
Tip: The final array element is removed each time pop() is called. The actual array is modified—no copy is created.
Ruby program that pops an array
# Create and display an array.
names = Array["Conrad", "James", "Joyce"]
puts names, ""
# Pop the last element.
names.pop()
puts names, ""
# Pop again.
names.pop()
puts names, ""
# Pop again and see if the array is empty.
names.pop()
puts names.empty?
Output
Conrad 3 elements
James
Joyce
Conrad 2 elements
James
Conrad 1 element
true 0 elements
Syntax: We declare an iteration variable between two vertical bars. It is important to learn the syntax here.
Tip: Each() enumerates over each element in the array. Here we use the identifier "number" to access elements.
Ruby program that uses each
# Some Wagstaff primes.
primes = [3, 11, 43, 683, 2731]
# Loop over primes and display them.
primes.each do |number|
puts number
end
Output
3
11
43
683
2731
Tip: We omit the "do" keyword and use curly brackets. This style makes it harder to add more statements.
Ruby program that uses each, short syntax form
# Some even numbers.
# ... Let's get even.
evens = [2, 4, 6, 8]
# Use short syntax form for the iterator block.
evens.each {|ev| puts ev}
Output
2
4
6
8
Here: We use each_index over a three-element array. It has indexes 0, 1 and 2. We print them.
Ruby program that uses each_index
# Array has indexes 0, 1 and 2.
values = ["cat", "dog", "sheep"]
# Loop over all indexes in the array.
values.each_index do |index|
puts index
end
Output
0
1
2
Important: If index() does not find the specified element, it returns nil. This is a special object.
NilRuby program that uses index
items = ["Boots", "Cloak", "Dagger"]
# Get index of this element.
result = items.index("Cloak")
puts result
# Call index again.
result = items.index("Dagger")
puts result
# Call index with nonexistent element.
result = items.index("Helmet")
if result == nil
puts "Not found"
end
Output
1
2
Not found
So: We start at zero. We progress to the inclusive maximum of the array's length minus one. We then access each element.
Advantages: With a for-loop, we can use the index in the loop iteration for other operations. We can access adjacent elements in the array.
Usually: The simplest syntax possible for an operation is best. This leads to simpler (and thus higher-quality) programs.
Ruby program that uses for-loop, array
# An array with four strings.
values = ["cat", "dog", "rabbit", "giraffe"]
# Loop over all indexes in the array.
for i in 0..values.length-1
# Access the element.
puts values[i]
end
Output
cat
dog
rabbit
giraffe
Ruby program that uses uniq
# Contains some duplicate elements.
values = [1, 1, 2, 3, 4, 4]
# Remove non-unique elements in-place.
values.uniq!
puts values
Output
1
2
3
4
Map: In other languages like Python, the map() built-in has similar functionality as collect.
Block: The syntax for collect requires a block. In this code we use the identifier "e," but other identifiers work just as well.
Ruby program that uses collect
# Contains three elements.
elements = [1, 0, 100]
# Use collect to multiply all elements by 2.
result = elements.collect{|e| e * 2}
# Display the result array.
p result
Output
[2, 0, 200]
Tip: Single elements too can be assigned. And often assigning one element at the time is easiest.
Ruby program that assigns range of elements
elements = [10, 20, 30, 40, 50]
# Assign range of elements at indexes 1, 2, and 3 to a new array.
elements[1..3] = [100, 200]
puts elements
Output
10
100
200
50
Sizing: Arrays are automatically resized. We have no need to specify how many elements will eventually be stored in them.
Terms: It is a topic of debate whether Array is technically a List. Often in languages, an Array is not resizable, but a list is.
Flatten: The flatten method converts a multidimensional array into one dimension. It copies all nested arrays.