Arrays in Ruby

Our first example demonstrates how to create and work with arrays in Ruby. Arrays are ordered, integer-indexed collections of any object.

# Here we create an array `a` that will hold exactly 5 integers.
# In Ruby, arrays are dynamic and can hold any type of object.
a = Array.new(5, 0)
puts "emp: #{a}"

# We can set a value at an index using the array[index] = value syntax,
# and get a value with array[index].
a[4] = 100
puts "set: #{a}"
puts "get: #{a[4]}"

# The length method returns the length of an array.
puts "len: #{a.length}"

# Use this syntax to declare and initialize an array in one line.
b = [1, 2, 3, 4, 5]
puts "dcl: #{b}"

# Ruby doesn't have a direct equivalent to Go's ... syntax for array initialization.
# However, you can use the Array.new method with a block for similar functionality.
b = Array.new(5) { |i| i + 1 }
puts "dcl: #{b}"

# Ruby doesn't have a direct equivalent to Go's index-based initialization.
# However, you can achieve similar results using Array.new and fill.
b = Array.new(5, 0)
b[0] = 100
b[3] = 400
b[4] = 500
puts "idx: #{b}"

# Array types in Ruby are one-dimensional, but you can create multi-dimensional
# arrays by nesting arrays.
two_d = Array.new(2) { Array.new(3, 0) }
2.times do |i|
  3.times do |j|
    two_d[i][j] = i + j
  end
end
puts "2d: #{two_d}"

# You can create and initialize multi-dimensional arrays at once too.
two_d = [
  [1, 2, 3],
  [1, 2, 3]
]
puts "2d: #{two_d}"

When you run this program, you’ll see:

$ ruby arrays.rb
emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
dcl: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [1, 2, 3]]

Note that arrays in Ruby are printed in the form [v1, v2, v3, ...] when using puts.

Ruby arrays are more flexible than arrays in many other languages. They can grow or shrink dynamically and can contain elements of different types. However, this example demonstrates how to use them in a way similar to the more rigid arrays in statically-typed languages.