Array Methods 1
Accessing Elements
You can get values from an array by using index positions. Ruby arrays start at index 0, so the first element is at 0, the second at 1, and so on.
Some common ways to access array elements:
firstandlastslicefetchinclude?values_at
For more information, please see Array Manipulation.
Array Comparison
Arrays are considered equal only when all three conditions are met.
- Same number of elements
- Same values in the same order
- Same casing for strings
Example:
tools = ["Git", "Docker", "Kubernetes"]
platforms = ["Git", "Docker", "Kubernetes"]
services = ["AWS", "Azure"]
utilities = ["Git", "Docker", "kubernetes"]
p tools == platforms
p tools == services
p tools == utilities
Output:
true
false
false
Notes:
- The first is
true; Same elements, same order, same casing. - The others are
false; Elements differ, either in content or casing.
Inequality is simply the reverse of equality. If arrays fail any equality rule, they are considered not equal.
p candy != desserts
p candy != vegetables
p candy != sweets
Output:
false
true
true
Notes:
- The first result is
falsebecause the arrays are equal. - The other results are
truebecause the arrays differ.
Spaceship Operator (<=>)
The spaceship operator is used to compare two values and returns a small set of predictable results that Ruby uses for sorting and comparisons.
- Returns
0when values are equal - Returns
-1when the left value is smaller - Returns
1when the left value is larger - Returns
nilwhen values cannot be compared
When comparing numbers, Ruby checks the left value against the right value.
Examples:
-
Both values are equal:
8 <=> 8Output:
0 -
The left value is smaller, so the result is
-1.8 <=> 20Output:
-1 -
If the left value is larger:
8 <=> 6Output:
1
This operator can also be used with arrays. Arrays are compared element by element, from left to right.
Example:
-
All elements match in the same order, so the arrays are equal.
[7, 8, 9] <=> [7, 8, 9]Output:
0 -
The first two elements are equal, but
7is smaller than10, so the left array is considered smaller.[4, 5, 7] <=> [4, 5, 10]Output:
-1 -
Here,
8is larger than6, so the left array is considered larger.[4, 5, 8] <=> [4, 5, 6]Output:
1
Order Matters
Note that order matters in arrays. Ruby stops comparing as soon as it finds a difference. Even though 8 is larger than 5, Ruby compares 10 and 5 first. Since 10 is larger, the result is 1.
[10, 5] <=> [5, 8]
Output:
1
If Ruby cannot logically compare two values, it returns nil.
7 <=> [1, 2, 3]
Output:
nil
Incomparable Values
A number and an array are different types, so they cannot be compared.
[nil, 1, 2] <=> [0, 1, 2]
Output:
nil
nil cannot be compared to a number, so the entire comparison fails.
This makes it clear when comparisons are invalid instead of guessing a result.
Adding Elements at the End
You can add new elements to the end of an array using built-in tools.
NOTE: All these options update the original array directly.
-
Using
pushThe
pushmethod appends elements to the end of an array and updates it in place.servers = ["web", "db", "cache"]
servers.push("auth")
p serversOutput:
["web", "db", "cache", "auth"]You can also add multiple elements at once.
servers.push("queue", "search")
p serversOutput:
["web", "db", "cache", "auth", "queue", "search"] -
Using
appendThe
appendmethod functions the same way aspush:databases = ["mysql", "postgres", "sqlite"]
databases.append("mongodb")
p databasesOutput:
["mysql", "postgres", "sqlite", "mongodb"]You can also append multiple elements:
databases.append("redis", "cassandra")
p databasesOutput:
["mysql", "postgres", "sqlite", "mongodb", "redis", "cassandra"] -
Using the Shovel Operator
<<The shovel operator adds elements to the end of an array using a shorter syntax.
locations = ["office", "warehouse", "store"]
locations << "factory"
p locationsOutput:
["office", "warehouse", "store", "factory"]You can chain the operator to add multiple elements in one line.
locations << "lab" << "data_center"
p locationsOutput:
["office", "warehouse", "store", "factory", "lab", "data_center"]This works the same way as
push, just with a more compact style.
insert
The insert method adds one or more elements at a specific index in an array, pushing existing elements forward.
- Specify the "index" as the first argument
- The "value(s)" to insert as the following argument(s)
The insert method modifies the original array and can add single or multiple values at any position. It also creates nil gaps if needed.
Example:
-
Single insert:
transactions = [19.99, 29.43, 3.87]
transactions.insert(1, 49.99)
p transactionsOutput:
[19.99, 49.99, 29.43, 3.87] -
Multiple inserts:
transactions.insert(0, 1.2, 3, 4.5)
p transactionsOutput:
[1.2, 3, 4.5, 19.99, 49.99, 29.43, 3.87] -
If index beyond array length:
numbers = [1, 2, 3]
numbers.insert(6, 1000)
p numbersOutput:
[1, 2, 3, nil, nil, nil, 1000]
pop
The pop method removes elements from the end of an array and returns them.
- Without an argument, it removes and returns the last element
- With an argument, it removes the elements and returns as a new array
- The original array is always updated
Example:
-
Without an argument:
flavours = ["Chocolate", "Kiwi", "Peach", "Plum", "Strawberry", "Taro"]
p flavours.pop
p flavoursOutput:
"Taro"
["Chocolate", "Kiwi", "Peach", "Plum", "Strawberry"] -
With an argument:
p flavours.pop(2)
p flavoursOutput:
["Peach", "Plum"]
["Chocolate", "Kiwi"]
shift and unshift
shift and unshift methods work like the opposite of pop and push.
shiftremoves the first element and returns itshiftwith a number returns that many elements as a new arrayunshiftadds one or more elements to the beginning, pushes existing elements forward
Examples:
-
Using
shiftwithout an argument:units = ["meter", "kilogram", "second", "amp"]
p units.shift
p unitsOutput:
"meter"
["kilogram", "second", "amp"] -
Using
shiftwith argument:p units.shift(2)
p unitsOutput:
["kilogram", "second"]
["amp"] -
Using
unshift:units.unshift("yard")
p units
units.unshift("inches", "miles")
p unitsOutput:
["yard", "amp"]
["inches", "miles", "yard", "amp"]
length and size
length returns how many elements exist in an array, regardless of type. size does the same thing.
a = ["a", "b", "c", "d"]
b = ["x", nil, "y"]
c = []
p a.length
p b.length
p c.length
p a.size
p b.size
p c.size
Output:
4
3
0
4
3
0
count
count can work in two ways depending on how it is used.
- Without arguments, it counts all elements.
- With an argument, it counts matching values only.
Example:
nums = [1, 2, 3, 4, 5, 2]
p nums.count
p nums.count(5)
p nums.count(2)
Output:
6
1
2
This makes count useful when you need to know how often a specific value appears in an array.
empty?
empty? checks whether an array has no elements.
- Returns
trueif the array has no items. - Returns
falseif at least one element exists.
Example:
a = ["one", "two"]
b = []
p a.empty?
p b.empty?
Output:
false
true
nil?
nil? checks whether an object is actually nil.
- Always
falsefor arrays. - Only
truewhen called onnil.
Example:
a = []
b = nil
p a.nil?
p b.nil?
Output:
false
true
uniq
You can remove repeated elements in an array using the uniq method.
uniqreturns a new array without duplicates.uniq!modifies the array in place, removing duplicates permanently.
Example:
tens = [13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13]
Using uniq does not change the original array:
p tens.uniq
p tens
Output:
[13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13]
[13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13]
To make the changes permanent, add the bang (!):
p tens
p tens.uniq!
p tens
Output:
[13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13]
[13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
split and join
Both split and join let you manipulate text in Ruby.
splitseparates a string into pieces at a delimiterjoinmerges array elements into a string with an optional delimiter- Both work with single characters, multiple characters, or spaces
Examples:
-
Using
splitwith default space delimiter:sentence = "Hi my name is James"
words = sentence.split
puts words.inspectOutput:
["Hi", "my", "name", "is", "James"] -
Using
splitwith a custom delimiter:sentence = "Hi.James.Loves.Coding"
words = sentence.split(".")
puts words.inspectOutput:
["Hi", "James", "Loves", "Coding"] -
Using
joinwithout a delimiter:words = ["Hi", "James", "Loves", "Coding"]
puts words.joinOutput:
HiJamesLovesCoding -
Using
joinwith a delimiter:puts words.join("-")Output:
Hi-James-Loves-Coding