Initializing Arrays

Learn how to initialize arrays in Ruby.

In this lesson, we’ll learn how to initialize a simple, one-dimensional array. There could be arrays with multiple dimensions, but for beginner programmers, two dimensions are usually enough. We will make sure to practice initializing, accessing, and iterating over 1D and 2D arrays, because it’s a very common pitfall during interviews. Sometimes, initializing arrays correctly is winning half the battle.

We are already familiar with the following syntax, which creates an empty array:

arr = []

Array with predefined values

If we want to initialize an array with predefined values, the program will look a bit different:

arr = ['one', 'two', 'three']

We can also get the size, or length, of the array with arr.size. Please note that methods in the Ruby language often have the same names. The String class has a size method, which returns the size of a string in characters. But, the size of the Array class will return the number of elements in that array. String class has the each_char method, so we can iterate over each character in a particular string. Arrays have a similar each method for iterating over each element. In other words, the principle of least surprise helps, and we can often guess the method for this or another class…

How to initialize arrays

There are multiple ways of initializing arrays in Ruby, and their results are identical:

arr = []

Alternative syntax:

arr = Array.new

Some consider it a language design flaw, because beginners will need to understand two ways of initializing an array, but they don’t work identically.

The advantage of the latter approach is the ability to pass additional parameters, like:

  • The size of the array (optional). An empty array will be initialized if the size is not provided.
  • Block (optional)
$ irb
> arr = Array.new(10)
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

Try these commands in the terminal below.

Get hands-on with 1200+ tech skills courses.