HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RubyVariablesData TypesOperatorsStringsArraysHash (Dictionary)Conditions (if / else)LoopsMethods (def)Classes
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🗂️ Hash (Dictionary)
🔁 Condition & Loop
🧩 Method & Class
Ruby›Arrays

Arrays

Array creation, appending (<<), mapping/selecting/summing, and iterating with each.

Simple enough for a 5-year-old to understand

Create and append to array

Example code
1
colors = ["red", "purple"]
Array.
DataArray.
2
colors << "green"
<< adds to the end.
Code<< adds to the end.
3
p colors
["red", "purple", "green"]
Output / Input["red", "purple", "green"]
4
puts colors.length
3
Output / Input3
DataCodeOutput / Input
💡 Hint: << is the most popular way to append (same as push).

About this topic

In Ruby, an array is an ordered collection of objects and can hold values of different types. Its size is not predetermined; it grows and shrinks as needed. An array is also an object, so there are numerous methods available on it.

Ruby's greatest power with arrays is its iterator methods. There are separate methods for iterating through elements one by one, transforming, filtering, and reducing them. Using these methods is both shorter and safer than writing manual loops.

A point to watch out for is negative indices: minus one gives the LAST element. This provides convenience, but when a calculated index accidentally falls into the negative, instead of an error, it returns an element from the end of the array, and the bug propagates silently.

What you will learn

  • Creating arrays and adding elements
  • What negative indices do
  • The difference between map, select, and each
  • That out-of-bounds access returns nil
  • The danger of modifying an array while iterating over it

When to use?

If you want to transform elements and get a new array, use map; if you want to filter, use select; if you just want to do something for each element, use each.

Writing manual counter loops over an array is not common in Ruby and carries the risk of off-by-one errors; iterator methods are both concise and safe.

Common mistakes

Wrong

numbers = [1, 2, 3]
doubled = numbers.each { |n| n * 2 }
puts doubled.inspect

each does not perform transformation; it discards the block's result and returns the ORIGINAL array. An unchanged array is printed to the screen, and no error message is received. map is used for a new transformed array; confusing these two is very common.

Correct

numbers = [1, 2, 3]
doubled = numbers.map { |n| n * 2 }
puts doubled.inspect

Wrong

numbers = [1, 2, 3]
puts numbers[10].round

An out-of-bounds index does not throw an error, it returns nil; then when a method is called on nil, you get the "undefined method 'round' for nil" error. The error surfaces a step away from the actual cause. To catch the error early, the fetch method is used.

Correct

numbers = [1, 2, 3]
value = numbers.fetch(10, 0)
puts value.round

Wrong

numbers = [1, 2, 3, 4]
numbers.each do |n|
  numbers.delete(n) if n.even?
end
puts numbers.inspect

Deleting elements while iteration is ongoing shifts the iterator's position and elements are skipped; the result turns out different than expected. There is no error message, the work is done incompletely and silently. Ruby's correct tool is the reject method: it produces a filtered new array.

Correct

numbers = [1, 2, 3, 4]
numbers = numbers.reject { |n| n.even? }
puts numbers.inspect

Frequently asked questions

What is the difference between map and each?

each executes the block for each element and returns the original array; it does not transform. map, on the other hand, collects the RESULT of the block on each call and produces a new array. If you want a new list of values, use map; if you only want a side effect, use each.

Why doesn't out-of-bounds access throw an error?

Ruby's design choice: if the index is out of bounds, it returns nil. This provides flexibility but delays errors. If you want the error to appear immediately, use fetch: if the index doesn't exist, it raises an error directly or returns the default value you provide.

What should I do to copy an array?

dup produces a shallow copy: the array is new, but the elements are the same objects. In nested arrays, modifying inner arrays is reflected in both copies. For a true deep copy, serializing with Marshal and deserializing is a common way.

Summary

Arrays can grow and hold values of different types together.

Negative indices count from the end; minus one is the last element.

map transforms, select filters, each only iterates.

Out-of-bounds indices return nil instead of an error; fetch reveals the error early.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code