Skip to content
the poor coder

Hackerrank Ruby Array - Initialization Solution

Poor Man
Published
Updated
Reading time
1 min read

One of the most commonly used data structures in Ruby is a Ruby Array, and below we see various methods of initializing a ruby array.

Your task is to initialize three different variables as explained below.

  • Initialize an empty array with the variable name array

Hint

Text
array = Array.new

or

Text
array = []
  • Initialize an array with exactly one nil element in it with the variable name array_1

Hint

Text
array_1 = Array.new(1)

or

Text
array_1 = [nil]
  • Initialize an array with exactly two elements with value 10 in it using the variable name array_2.

Hint

Text
array_2 = Array.new(2, 10)

or

Text
array_2 = [10, 10]

Solution in ruby#

Approach 1.

Python
array = []
array_1 = Array.new(1)
array_2 = Array.new(2) { 10 }

Approach 2.

Python
array = Array.new
array_1 = Array.new(1)
array_2 = Array.new(2, 10)

Approach 3.

Python
# Initialize 3 variables here as explained in the problem statement
array = []
array_1 = [nil]
array_2 = [10, 10]

Keep going

ESC