0
0
Rubyprogramming~5 mins

Array creation methods in Ruby

Choose your learning style9 modes available
Introduction

Arrays help you store many items together in one place. Creating arrays is the first step to use them.

When you want to keep a list of your favorite fruits.
When you need to store multiple numbers to add later.
When you want to group names of your friends.
When you want to create an empty list to add items later.
When you want to create an array with repeated values.
Syntax
Ruby
array = [item1, item2, item3]

empty_array = []

array = Array.new(size)

array = Array.new(size, default_value)

You can create arrays by listing items inside square brackets [].

Array.new creates a new array with a given size and optional default value.

Examples
Creates an array with three fruit names.
Ruby
fruits = ["apple", "banana", "cherry"]
Creates an empty array with no items.
Ruby
empty_list = []
Creates an array with 3 nil values: [nil, nil, nil]
Ruby
numbers = Array.new(3)
Creates an array with 4 zeros: [0, 0, 0, 0]
Ruby
zeros = Array.new(4, 0)
Sample Program

This program shows different ways to create arrays and prints them.

Ruby
fruits = ["apple", "banana", "cherry"]
puts "Original fruits array:"
puts fruits.inspect

empty_array = []
puts "Empty array:"
puts empty_array.inspect

numbers = Array.new(3)
puts "Array with 3 nils:"
puts numbers.inspect

zeros = Array.new(4, 0)
puts "Array with 4 zeros:"
puts zeros.inspect
OutputSuccess
Important Notes

Creating arrays with Array.new(size, value) sets all elements to the same object, so be careful with mutable objects.

Using [] is the simplest way to create arrays with known items.

Empty arrays are useful when you want to add items later.

Summary

Arrays store multiple items in one variable.

You can create arrays by listing items or using Array.new.

Empty arrays and arrays with default values are common starting points.