Arrays in Ruby

Arrays are ordered collections of objects. They can hold any type of Ruby object: numbers, strings, other arrays, hashes, classes and methods.

Here is what a basic array looks like and is used for:

arr = [1,2,3,4]

arr.each do |a|
  puts a
end

# => 1
# => 2
# => 3
# => 4

Arrays are created by placing a list of objects between square brackets.

number_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

array_full_of_lots_of_things = [55, "55", 55.0, [5, 5]]

Accessing arrays

The data in these arrays can be accessed easily like this:

number_array[0] # 1
number_array[1] # 2
number_array[2] # 3
number_array[3] # 4

Maybe you weren’t expecting this result. What is happening when you access an array like this: `number_array[0]` is that you are asking for the object at the 0th position in the array (which happens to be the number 1). This “position” is called the index and in Ruby the first position in the index is 0 (it goes up by 1 for each position).

So what comes out of `array_full_of_lots_of_things[3]`?

array_full_of_lots_of_things[3] # [5, 5]

The array of `[5, 5]` is the object at position with the index of 3 in `array_full_of_lots_of_things`.

Speaking of indexing, Ruby can do negative indexing which basically means you can count backwards in an array.

number_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
number_array[-1] # 10
number_array[-2] # 9
number_array[-3] # 8

The -1, -2, and -3 simply start at the end of the array and return the data that is there.

Adding and Removing Objects to/from an Array

There are two simple ways to add an object to the end of an array. The `push` method and the `<<` operator. Here is how they work:

little_array = [1]
little_array.push(34)
little_array # [1, 34]
little_array << 66
little_array # [1, 34, 66]

As you can see both methods add the new object to the end of the array so the additions will always come after the elements that are already inside the array.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *