Revisiting Ruby Essentials: Arrays and Strings

Introduction

Welcome to the next unit of this course!

Before we delve deeper into essential Ruby concepts, particularly for interview preparation, we need to revisit some of Ruby's features—specifically, Ruby collections: Arrays and Strings. These collections allow Ruby to group multiple elements, such as numbers or characters, into a single entity.

Some of these concepts might already be familiar to you, so you can breeze through the beginning until we get to the more complex topics and paths.

Understanding Ruby's Collections

At our starting point, it's crucial to understand what Ruby collections are. They help us manage multiple values efficiently. We will mainly focus on Arrays and Strings in Ruby. An interesting fact here is that both arrays and strings are mutable in Ruby, meaning you can directly modify their contents. Let’s see examples:

# Defining an array and a string
my_array = [1, 2, 3, 4]
my_string = 'hello'

# Now let's try to change the first element of both collections
my_array[0] = 100         # Directly modifies the array to [100, 2, 3, 4]
my_string[0] = 'H'        # Directly modifies the string to "Hello"

puts my_array.inspect      # Output: [100, 2, 3, 4]
puts my_string             # Output: "Hello"

In this example, we see that both the array and the string were modified in place. Ruby’s mutability allows us to change them directly, which can be quite powerful!

Diving Into Arrays

Imagine having to take an inventory of all flora in a forest without an array at your disposal — seems nearly impossible, right? That's precisely the purpose Arrays serve in Ruby. They let us organize data so that each item holds a definite position or an index. The index allows us to access or modify each item individually.

Working with Arrays is as simple as this:

# Creating an array
fruits = ['apple', 'banana', 'cherry']

# Add a new element at the end using push
fruits.push('date') # ['apple', 'banana', 'cherry', 'date']

# Adding an element at the end using <<
fruits << 'elderberry' # ['apple', 'banana', 'cherry', 'date', 'elderberry']

# Inserting an element at a specific position
fruits.insert(1, 'bilberry') # ['apple', 'bilberry', 'banana', 'cherry', 'date', 'elderberry']

# Removing all occurrences of a particular element
fruits.delete('banana') # ['apple', 'bilberry', 'cherry', 'date', 'elderberry']

# Accessing elements using indexing
first_fruit = fruits[0]       # apple
last_fruit = fruits[-1]       # elderberry

# You can also use .first and .last for similar results
first_fruit_alt = fruits.first # apple
last_fruit_alt = fruits.last   # elderberry

Note that both push and << can be used to add elements to the end of an array. Use << for quick, single additions and push when adding multiple elements at once.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal