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

Array Creation

In this page:

  1. Array Creation

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
🔒

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.