Push It to The Limit - Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Push It to The Limit

Arrays aren't limited to strings. Let's create an array of numbers.

num_array = [1, 2, 3]

Imagine there are certain situations in which we want to add some more elements to this array. How can we do this without actually going and manually entering them in?

num_array.push(4, 5)

print num_array

[1, 2, 3, 4, 5]

As shown, push followed by the new items is how we add to our array.

But wait, there's more! This method adds the items to the end of the array. We feel the need to put them in front.

num_array.unshift(-1, 0)

print num_array

[-1, 0, 1, 2, 3, 4, 5]

That's fancy. We aren't limited to one data type in our arrays. We also aren't limited to just placing something in the front or back.

num_array.insert(4, "Squeezing in here.")

print num_array

[-1, 0, 1, 2, "Squeezing in here.", 3, 4, 5]

Recall that the first position in an array takes the spot of [0]. We choose where we want our new item placed with the first parameter number. The four in (4, "Squeezing in here.") is what's indicating to Ruby where we want "Squeezing in here." inserted. Let's add a float between four and five in our array.

num_array.insert(7, 4.5)

print num_array

[-1, 0, 1, 2, "Squeezing in here.", 3, 4, 4.5, 5]

We can also delete items in our array using delete.

num_array.delete(-1)

print num_array

[0, 1, 2, "Squeezing in here.", 3, 4, 4.5, 5]

That's cool. We can even save time by targeting the element to delete by its index number. Let's trash "Squeezing in here".

num_array.delete_at(3)

[0, 1, 2, 3, 4, 4.5, 5]