Menu
Coddy logo textTech

Creating Arrays

Part of the Fundamentals section of Coddy's Ruby journey — lesson 58 of 88.

An array is an ordered collection of elements. Think of it as a list that can hold multiple values in a single variable. Arrays are incredibly useful when you need to work with groups of related data.

To create an array in Ruby, use square brackets [] with elements separated by commas:

numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
puts fruits  # Outputs each fruit on a new line

Ruby arrays can hold any type of data, and you can even mix different types in the same array:

mixed = [42, "hello", true, 3.14]

You can also create an empty array and add elements later:

empty_list = []

To check how many elements an array contains, use the length or size method:

colors = ["red", "green", "blue"]
puts colors.length  # Outputs: 3

Arrays maintain the order of their elements, so the first item you add stays first, the second stays second, and so on. This ordering becomes important when we learn to access individual elements in the next lesson.

challenge icon

Challenge

Easy

Read three inputs:

  1. A string (first element)
  2. An integer (second element)
  3. A string (third element)

Create an array containing these three elements in the order they were received. Then print the array using puts, followed by the array's length on a new line.

For example, if the inputs are apple, 42, and banana, the output should be:

apple
42
banana
3

If the inputs are red, 100, and blue, the output should be:

red
100
blue
3

If the inputs are hello, 7, and world, the output should be:

hello
7
world
3

Cheat sheet

An array is an ordered collection of elements that can hold multiple values in a single variable.

Create an array using square brackets [] with elements separated by commas:

numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]

Arrays can hold any type of data, including mixed types:

mixed = [42, "hello", true, 3.14]

Create an empty array:

empty_list = []

Print an array using puts (outputs each element on a new line):

puts fruits

Get the number of elements using length or size:

colors = ["red", "green", "blue"]
puts colors.length  # Outputs: 3

Try it yourself

# Read inputs
first_element = gets.chomp
second_element = gets.to_i
third_element = gets.chomp

# TODO: Write your code below
# Create an array with the three elements


# Print the array using puts, then print the array's length
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals