Arrays Cheat Sheet

Name Description Syntax Examples
Array literal Creates a new array [item1, item2, …] my_array = [1, 2, 3]
Array.new Creates a new empty array (equivalent to []) Array.new my_array = Array.new
length Returns the length of the array (the number of items it contains) array.length my_array.length
Index operator Lets you access the item at a given position within an array array[index] my_array[1]
delete_at Deletes the item at a given index and returns it array.delete_at(index) my_array.delete_at(1)
each Lets you iterate over all elements in an array array.each do |item|

end
my_array.each do |item|
puts item
end
first Returns the very first item of the array array.first my_array.first
last Returns the very last item of the array array.last my_array.last
include? Returns a boolean, whether the array contains a certain element or not array.include?(item) my_array.include?(4)
pop Removes the last item of the array and returns it array.pop my_array.pop
push or << Adds an item to the end of the array array.push(item)
array << item
my_array.push(4)
my_array << 4
reverse Returns a copy of the array with the elements in reverse order array.reverse my_array.reverse
sort Returns a sorted copy of the array array.sort [5, 2, 4].sort
uniq Returns a copy of the array with duplicates removed array.uniq [1, 1, 2, 2].uniq