TExcelTAD
Home › Ruby › Ruby Arrays

Ruby Arrays

An array is an ordered list of values. Arrays can hold any mix of objects, grow and shrink as needed, and come with a rich set of methods.

Creating arrays

ruby · try it yourself
empty = []
numbers = [3, 1, 4, 1, 5]
mixed = [1, "two", :three, 4.0, nil, [5, 6]]
words = %w[red green blue]
zeros = Array.new(4, 0)
squares = Array.new(5) { |i| i * i }

p empty, numbers, mixed, words, zeros, squares
[]
[3, 1, 4, 1, 5]
[1, "two", :three, 4.0, nil, [5, 6]]
["red", "green", "blue"]
[0, 0, 0, 0]
[0, 1, 4, 9, 16]

%w[...] builds an array of strings from words, saving you all the quotes and commas.

Accessing elements

Indexes start at 0; negative indexes count from the end:

ruby · try it yourself
langs = ["Ruby", "Go", "Rust", "Elixir", "Zig"]
p langs[0]
p langs[-1]
p langs[1, 2]      # start, count
p langs[1..3]      # range
p langs.first
p langs.last(2)
p langs[10]
p langs.dig(0)
p langs.fetch(1)
"Ruby"
"Zig"
["Go", "Rust"]
["Go", "Rust", "Elixir"]
"Ruby"
["Elixir", "Zig"]
nil
"Ruby"
"Go"

fetch is the strict alternative to []: it raises IndexError for a missing index instead of returning nil (or returns a default you pass in: langs.fetch(10, "none")).

Adding and removing

ruby · try it yourself
queue = ["a", "b"]
queue << "c"           # append (most common)
queue.push("d", "e")    # append several
queue.unshift("z")      # add at the front
queue.insert(2, "NEW")  # insert at index 2
p queue

p queue.pop            # remove last
p queue.shift          # remove first
p queue.delete("NEW")  # remove by value
p queue.delete_at(0)   # remove by index
p queue
["z", "a", "NEW", "b", "c", "d", "e"]
"e"
"z"
"NEW"
"a"
["b", "c", "d"]
Method Where Returns
<< / push end the array
unshift start the array
insert(i, x) at index i the array
pop / shift end / start the removed element
delete(x) all occurrences of x x (or nil)
delete_at(i) index i the removed element

Changing elements

ruby · try it yourself
grid = [1, 2, 3, 4, 5]
grid[0] = 100
grid[-1] = 500
grid[1..2] = [:x]     # replace a slice
p grid
grid[7] = "far"       # gaps are filled with nil
p grid
[100, :x, 4, 500]
[100, :x, 4, 500, nil, nil, nil, "far"]

Size and membership

ruby · try it yourself
bag = ["pen", "key", "pen", "coin"]
p bag.length
p bag.size
p bag.count("pen")
p bag.include?("key")
p bag.index("pen")
p bag.empty?
p bag.uniq
4
4
2
true
0
false
["pen", "key", "coin"]

Iterating

ruby · try it yourself
temps = [18, 21, 25, 19]
temps.each { |t| print t, "°C " }
puts
temps.each_with_index { |t, day| puts "Day #{day + 1}: #{t}" if t > 20 }
18°C 21°C 25°C 19°C
Day 2: 21
Day 3: 25

Combining arrays

ruby · try it yourself
a = [1, 2, 3]
b = [3, 4]
p a + b       # concatenate
p a - b       # difference
p a & b       # intersection
p a | b       # union (no duplicates)
p a * 2       # repeat
p [a, b].flatten
p a.zip(b)
[1, 2, 3, 3, 4]
[1, 2]
[3]
[1, 2, 3, 4]
[1, 2, 3, 1, 2, 3]
[1, 2, 3, 3, 4]
[[1, 3], [2, 4], [3, nil]]

Nested arrays and destructuring

ruby · try it yourself
board = [
  ["X", "O", "X"],
  [" ", "X", "O"],
  ["O", " ", "X"],
]
puts board[1][2]
board.each { |row| puts row.join("|") }

point = [4, 7]
x, y = point
puts "x=#{x} y=#{y}"

[[:ann, 31], [:bo, 25]].each { |name, age| puts "#{name} is #{age}" }
O
X|O|X
 |X|O
O| |X
x=4 y=7
ann is 31
bo is 25

When a block receives an array but declares two parameters, Ruby automatically splits the array into them.

Tip: Be careful with Array.new(3, []) — all three slots refer to the same inner array. Use Array.new(3) { [] } to get three separate arrays.

Test yourself

What does [10, 20, 30][-1] return?

  1. 10
  2. 30
  3. nil
  4. IndexError

What does arr.pop return?

  1. The array without the last element
  2. The removed last element
  3. nil
  4. The first element

What is [1, 2, 2, 3] - [2]?

  1. [1, 2, 3]
  2. [1, 3]
  3. [1, 2, 3, 2]
  4. An error