Skip to content

Chapter 1 of 7

Core Data Structures

Ruby provides several built-in data structures for organizing information in programs. A Symbol is a lightweight, immutable identifier written with a leading colon, such as :status or :id. Because each symbol is stored in memory only once, symbols are more efficient than strings when used as keys or repeated identifiers, and they are commonly seen as hash keys or method names passed around a program.

An Array is an ordered, indexed collection of objects. Arrays can be created with square brackets, such as nums = [1, 2, 3], or with the percent-w shortcut for word arrays, like words = %w[hello world]. The Array.new constructor accepts a size and a default value, so Array.new(5, 0) produces an array of five zeros. Arrays preserve insertion order and can hold mixed object types.

A Hash stores data as key-value pairs and is created with curly braces or Hash.new. The shorthand h = { name: "Alice", age: 30 } uses symbols as keys; the colon before each key turns it into :name and :age behind the scenes. Hash.new(0) sets a default value of zero for missing keys, and values are accessed with square brackets, for instance h[:name]. A Range represents an interval of values using either two dots for an inclusive range like (1..5) or three dots for an exclusive range like (1...5). Ranges work with numbers, strings, and any object that implements the spaceship operator.

All chapters
  1. 1Core Data Structures
  2. 2Blocks, Procs, and Lambdas
  3. 3Classes, Inheritance, and Modules
  4. 4Iterators and Functional Collections
  5. 5Exception Handling and File I/O
  6. 6Strings, Patterns, and Operators
  7. 7Metaprogramming and the Ruby Ecosystem

Drill it

Reading is not remembering. These come from the Ruby Programming deck:

Q

What is a Symbol in Ruby?

A Symbol is a lightweight, immutable identifier prefixed with a colon, e.g. :name. Symbols are stored in memory only once, making them more efficient than strin...

Q

How do you create an Array in Ruby?

An Array is an ordered collection created with square brackets or Array.new.Examples:nums = [1, 2, 3]words = %w[hello world]empty = Array.new(5, 0)

Q

How do you create a Hash in Ruby?

A Hash is a collection of key-value pairs.Examples:h = { name: "Alice", age: 30 }h = Hash.new(0)Access values with h[:name].

Q

What is a block in Ruby?

A block is an anonymous chunk of code enclosed in do...end or curly braces { } that can be passed to a method.Example:[1,2,3].each { |n| puts n }