In Ruby, an array is an ordered collection of objects, which can hold multiple data types, including numbers, strings, other arrays, or even objects. Of the languages we’ve looked at, it is most similar to lists in Python, where you can store dynamic types, and they are dynamically sized.
There are a couple of ways you can create an array, including by giving it values, as well as creating an empty array:
# Using square brackets
numbers = [1, 2, 3, 4, 5]
# Using Array.new
empty_array = Array.new
# Using Array.new with a set of default values
array_with_defaults = Array.new(3, "default") # ["default", "default", "default"]
Accessing elements is fairly straightforward if you have worked with a language like Python. You can use either positive or negative indexes. If you use a positive index, the first element is 0, as is a zero based numbering system.
letters = ['a', 'b', 'c']
letters[0]
# 'a'
letters[1]
# 'b'
letters[-1]
# 'c'
If you go outside the size of the array, you will get a nil
value returned to you.
Adding New Elements to an Array
numbers.push(6) # => [1, 2, 3, 4, 5, 6]
numbers << 7 # => [1, 2, 3, 4, 5, 6, 7]
numbers.unshift(0) # => [0, 1, 2, 3, 4, 5, 6, 7]
Notice that unshift
puts the value at the beginning of the array.
Removing Elements from and Array
letters.pop # Removes the last element
letters.shift # Removes the first element
letters.delete("b") # Deletes the element with a value `b`
Searching an Array
You can easily search for an element in an array, unlike some languages where you’d have to build that feature yourself, in Ruby, it’s provided for you.
numbers.include?(3) # => true
Other things you can do
There are other methods you can use such as:
flatten
– merge nested arrays into a single arraysort
– sort the elements of an arrayuniq
– find the unique elements of an array
Hashes in Ruby
In Ruby, hashes are collections of key-value pairs, similar to dictionaries or maps in other languages.
While they might seem similar to arrays in many ways, they differ significantly from arrays in how they organize and access data.
Key Features of Hashes:
Feature | Array | Hash |
---|---|---|
Structure | Ordered list of elements | Key-value pairs |
Access by | Integer-based index, Indexes start at zero | Key (any object can be a key) |
Use Case | Ordered collections or lists | Lookup tables or dictionaries |
Example | [1, 2, 3] | { name: "Alice", age: 25 } |
Accessing Data
Access values by their keys.
hash = { name: "Alice", age: 25 }
hash[:name] # => "Alice"
Adding/Updating Elements:
Add or update key-value pairs.
hash[:city] = "New York"
hash # => { name: "Alice", age: 25, city: "New York" }
Iteration:
Use methods like each
to iterate over keys and values.
hash.each { |key, value| puts "#{key}: #{value}" }
When to Use a Hash:
Use hashes when you need to associate keys with values, such as:
- Storing attributes about something, but don’t want to use a class:
user = { name: "Alice", age: 25, city: "New York" }
- Configuration settings:
config = { theme: "dark", language: "en", timezone: "UTC" }
- Lookup tables:
status_codes = { 200 => "OK", 404 => "Not Found", 500 => "Internal Server Error" }
Ruby Arrays and Hashes was originally found on Access 2 Learn