Ruby For Programmers of Other Languages: Arrays

Every programming language, or at the least the languages I’ve programmed in, make use of arrays and ruby is no exception even though the syntax might be a little different.

Defining an Array

Like with other variables in ruby array names do not have to be preceded by special keywords, you can just simply provide an array with the values you need, like this.

myArray=[23,45,67,89]
puts myArray[2]

The result of the previous snippet would show the number 67 because as you might have guessed an array index starts at 0.

Since the array index is a number you can use any other variable in place of the index. Let’s say you had a variable called “y” with a value of 2, then the following code will give the same result as the previous.

myArray=[23,45,67,89]
y=2
puts myArray[y]

String Arrays

Arrays in Ruby can hold strings and integers at the same. Let’s take the previous code and throw in a couple of strings.

myArray=[23,45,"orange",67,89,"apple"]
puts myArray[2]
# results in "orange"

Associative Arrays

These type of arrays let you use words instead of numbers as keys for the arrays, which can be very helpful when working with databases.

To better illustrate this I will make an associative array to hold a user’s information.

user={
"first_name"=>"Will",
"last_name"=>"Smith"
}

puts user["first_name"]+' '+user['last_name']

# results in "Will Smith"

Methods For Arrays

There are special functions that one can use on arrays, two such functions are "reverse" and "join" for example.

The method "join" concatenates all the indexes in the array, "reverse" reverses the order in which values were specified.

To see methods you can use on arrays read my post on reflection in Ruby.