In Ruby, you can represent ordered collections of objects using arrays.
Here's a basic array:
x = [1, 2, 3, 4]
This array has four elements.
Each element is an integer, and is separated by commas.
Square brackets are used to denote an array literal.
Elements can be accessed by their index.
To access a particular element:
x = [1, 2, 3, 4] puts x
The indexing for Ruby's arrays starts from 0, so the first element of the array is element 0, and the second element of the array is element 1, and so on.
x is addressing the third element of the array.
To change an element, you can simply assign it a new value or manipulate it:
x = [1, 2, 3, 4] x += 1 puts x
x = [1, 2, 3, 4] x = "test" * 3 puts x
Arrays don't need to be set up with predefined entries or have elements allocated manually.
You can create an empty array like so:
x = 
The array is empty, and trying to address, say, x results in nil being returned.
You can add things to the end of the array by pushing data into it, like so:
x =  x << "Word"
After this, the array contains a single element: a string saying "Word".
With arrays, << is the operator for pushing an item onto the end of an array.
You can also use the push method, which is equivalent:
You can remove entries from an array one by one.
Arrays act as a "last in, first out" system where items can be pushed onto the end but also popped from the end.
Popping is the process of retrieving and removing items from the end of the array.
x =  x << "A" # w ww . ja v a 2s. c om x << "B" x << "C" puts x.pop puts x.pop puts x.length
You can join all the elements together into one big string by calling the join method on the array:
x = ["A", "B", "C"] puts x.join
The join method can take an optional parameter that's placed between each element in the resulting string:
x = ["A", "B", "C"] puts x.join(', ')
This time you join the array elements together, but between each set of elements you place a comma and a space.