← Back to Ruby Course | Chapter 4: Arrays | Lesson 1 of 7

Array Creation

An array is an ordered list of items kept together, like a row of lockers with numbers. You can create one with square brackets and fill it with anything.

In this page:

  1. Array Creation
Syntax
ruby
array = [value1, value2, value3]
array = Array.new(size, default_value)
array = %w[word1 word2 word3]

Array Creation

A Ruby array is created with square brackets, [1, 2, 3], or with Array.new, and can hold elements of mixed types since Ruby is dynamically typed.

Arrays are ordered and zero-indexed. Array.new(n) { |i| ... } builds an array by calling a block for each index, useful for generating data programmatically.

Note: Array.new(5) { |i| i * i } builds [0, 1, 4, 9, 16] in one line without a separate loop.

Example: Array Creation

markup
fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, true]
squares = Array.new(5) { |i| i * i }

puts fruits.inspect
puts mixed.inspect
puts squares.inspect
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using Array.new(3, []), where all elements are the same array object; use Array.new(3) { [] }.
  2. Using an index beyond the length such as fruits[10], which returns nil rather than an error.
  3. Writing %w[a b c] with commas, which puts the commas inside the strings.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.