Error:
Create empty array
# literal
arr = []
# constructor
arr = Array.new()
Create array with elements
# literal
arr = [1, 2, 3]
# Constructor
arr = Array.new(3, 1) # [1, 1, 1]
Get number of elements in the array
arr = [1, 2, 3]
total = arr.length # 3
count = arr.length # 3
Check if array is empty
arr = []
b = arr.empty? # => true
Join elements of the array with string
['1', '2', '3'].join('/') # => '1/2/3'
Remove particular value from the array
arr = [7, 8, 9]
arr.delete(8) # arr is [7, 9]
Remove element at index from the array
arr = [7, 8, 9]
arr.delete_at(2) # arr is [7, 8]
Remove last element from the array
arr = [7, 8, 9]
arr.pop() # => 9
arr # => [7, 8]
Remove first element from the array
arr = [7, 8, 9]
arr.shift() # => 7
arr # => [8, 9]
Add element to the end of the array
arr = [7, 8, 9]
arr.push(10) # => [7, 8, 9, 10]
arr << 11 # => [7, 8, 9, 10, 11]
Add element to the beginning of the array
arr = [7, 8, 9]
arr.unshift(10) # => [10, 7, 8, 9]
Get subarray of the array
arr = [7, 8, 9, 10, 11]
arr[2..3] # => [9, 10]
arr.slice(-3, 2) # => [9, 10]
Replace subarray of the arary with another array
arr = [7, 8, 9, 10, 11]
arr2 = [0, 1, 2]
arr.slice!(2, 2)
arr.insert(2, *arr2)
arr # => [7, 8, 0, 1, 2, 11]
Iterate over all elements of the array
[0, 1, 2].each do |el|
puts "--> #{el}"
end
Get unique elements of the array
arr = [1, 1, 2, 2, 3, 3]
arr.uniq # => [1, 2, 3]
arr # => [1, 1, 2, 2, 3, 3]
arr.uniq!
arr # => [ 1, 2, 3]
Get difference between two arrays
[1, 2, 3, 4] - [3, 4, 7, 8] # => [1, 2]
Get intersection of two arrays
[1, 2, 3, 4] & [3, 4, 7, 8, 4] # => [3, 4]
Get union of two arrays
[1, 2, 3, 4] | [3, 4, 7, 8, 4] # => [1, 2, 3, 4, 7, 8]
Append one array to another
[1, 2] + [2, 3] # => [1, 2, 2, 3]
a = ['a', 'b']
a += [2, 3] # a is ['a', 'b', 2, 3]
Reverse the array
arr = [1, 2, 3]
arr.reverse # => [3, 2, 1]
arr # => [1, 2, 3]
arr.reverse! # => [3, 2, 1]
arr # => [3, 2, 1]
Find first element of the array that passes test
arr = [1, 2, 3, 4, 5]
arr.index { |x| x % 2 == 0 } #=> 1
Find last element of the array that passes test
arr = [1, 2, 3, 4, 5]
arr.rindex { |x| x % 2 == 0 } #=> 3
Find all elements of the array that pass test
arr = [1, 2, 3, 4, 5]
arr.find_all { |x| x % 2 == 0 } #=> [2, 4]
Sort the array
arr = ["t", "e", "s", "t"]
arr.sort # => ["e", "s", "t", "t"]
arr # => ["t", "e", "s", "t"]
arr.sort! # => ["e", "s", "t", "t"]
arr # => ["e", "s", "t", "t"]
Sort the array using compare function
arr = ["1", "2", "10", "11"]
# lexical
arr.sort { |x,y| x <=> y } # => ["1", "10", "11", "2"]
# numerical
arr.sort { |x,y| x.to_i <=> y.to_i } # => ["1", "2", "10", "11"]
Shuffle the array
[1, 2, 3, 4].shuffle
Map elements of the array
[1,2,3,4].map { |x| x*x } # => [1, 4, 9, 16]
Check if the array contains the element
[1, 2, 3, 4].include?(5) #=> false
[1, 2, 3, 4].include?(3) #=> true
Find maximum number in the array
[1, 5, 2, 3].max # => 5
Find minimum number in the array
[1, 5, -2, 3].min # => -2