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.
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:
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!
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:
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.
Think of Strings as a sequence of letters or characters. So whether you're writing down a message or noting a paragraph, it all boils down to a string in Ruby. Strings are enclosed by either single or double quotes.
In Ruby, strings are mutable, meaning we can alter them directly, as shown previously. However, many string methods return modified copies instead of altering the original string directly. Examples include downcase
, upcase
, strip
, etc.
Both arrays and strings allow us to access individual elements through indexing. In Ruby, we start counting from 0, meaning the first element is at index 0, the second at index 1, and so on. Negative indexing begins from the end, with -1
denoting the last element.
We have many operations we can perform on arrays and strings. We can slice them, concatenate them, repeat them, and even find the occurrence of a particular element!
And there we have it, a Ruby toolkit for working with arrays and strings!
Give yourself a pat on the back! You've navigated through Ruby collections, primarily focusing on Arrays and Strings, learning how to create, access, and manipulate them via various operations.
Up next, reinforce your understanding with plenty of hands-on practice. Understanding these concepts, combined with frequent practice, will enable you to tackle more complex problem statements with ease. Happy coding in Ruby!
